powershellwrite-host

Write-Host and Log on one line?


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!


Solution

  • 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.)