简体   繁体   中英

Setting a cmdlet to a variable without immediately calling it

Finding this is the case with a few cmdlets (eg Write-Host, Read-Host). Just wondering how to get around it.

For example, I have a formatted Write-Host string I would like to set to a variable. But it calls the variable as soon as it's defined. Seems the only way to avoid it is to create a function, which seems like overkill.

function Test-WriteHost
{
    $inFunction = Write-Host "I'm in a variable!" -BackgroundColor DarkBlue -ForegroundColor Cyan
}

$direct = Write-Host "So am I!" -BackgroundColor DarkBlue -ForegroundColor Cyan

So am I!

You don't really need a function. A simple scriptblock will do:

$direct = {Write-Host "So am I!" -BackgroundColor DarkBlue -ForegroundColor Cyan}

The you can just invoke the scriptblock:

&$direct

The usual thing to do here would be to use functions instead of variables.

function FormattedWriteHost([string]$message)
{
    Write-Host $message -BackgroundColor DarkBlue -ForegroundColor Cyan
}

and then you can call this function at your leisure:

PS C:\> FormattedWriteHost "I'm in a function!"
I'm in a function!

This is not overkill. write-host does not "return" anything - it simply writes output. You'll notice that your variables are actually empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM