Write-Host and Log on one line?

4.9k views Asked by At

I'm very new to PowerShell, and self-teaching myself it at that. My question is can you have 'write-host' and 'log-write' on the same line, to run as one action?

What I have is this:

Write-Host "Node Id is $nodeProps["NodeID"]" 
LogWrite "Node Id is $nodeProps["NodeID"]"

But I'm wondering if there is a way to do it like:

Write-Host, LogWrite "Node Id is $nodeProps["NodeID"]"

Thanks for any and all help!

2

There are 2 answers

6
mklement0 On BEST ANSWER

You can use a pipeline with the ForEach-Object cmdlet (% is its built-in alias) as follows:

"Node Id is $($nodeProps["NodeID"])" | % { Write-Host $_; LogWrite $_ }

Note how the reference to $nodeProps["NodeID"] needs to be enclosed in $(...) to work.

If you need this repeatedly, define a (simple) function:

function writeAndLog([string] $msg) { Write-Host $msg; LogWrite $msg }

writeAndLog "Node Id is $($nodeProps["NodeID"])"

P.S.: Prompted by campbell.rw's comments:

If you don't like the idea of using ForEach-Object - which is typically used to loop over multiple input objects - on a single input item, you can use a script block, with &, the call operator:

& { Write-Host $args[0]; LogWrite $args[0] } "Node Id is $($nodeProps["NodeID"])"

$args is the collection of all (unbound) arguments, so $args[0] refers to the first one. (In this particular case, just referencing $args would have worked too.)

2
Mathias R. Jessen On

You can use Tee-Object cmdlet to copy the pipeline stream to a file:

"Node Id is $($nodeProps["NodeID"])" |Tee-Object -FilePath C:\dev\test2.txt -Append |Write-Host