Local Needs
Local Needs

Reputation: 569

Setting a cmdlet to a variable without immediately calling it

Finding this is the case with a few cmdlets (e.g. 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!

Upvotes: 1

Views: 65

Answers (2)

mjolinor
mjolinor

Reputation: 68243

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

Upvotes: 3

Nacht
Nacht

Reputation: 3494

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.

Upvotes: 1

Related Questions