Powershell logging from invoke-command

☆樱花仙子☆ 提交于 2019-12-05 17:25:33

As documented, Invoke-Command returns all command output, so you could use Write-Output instead of Write-Host and pipe the returned output into a file. There's no fancy coloring with Write-Output, though. You could, however, write 'Info', 'Warn' and 'Error' level messages to the correct streams using Write-Output, Write-Warning and Write-Error. Also, you may want to suppress output from regsvr32.

foreach ($server in $servers) {
  Invoke-Command -Computer $server -ScriptBlock {
    Param($server)

    Function write-log {
      ...
      switch ($Level) {
        'Error' { Write-Error $msg }
        'Warn'  { Write-Warning $msg }
        'Info'  { Write-Output $msg }
      }
    }

    write-log -message 'Begin DLL registration for $server' -level Info
    $RegFile = "cimwin32.dll"
    regsvr32 $RegFile /s | Out-Null
    write-log -message 'registered $RegFile' -level Info
    write-log -message 'End DLL registration for $server' -level Info
  } -ArgumentList $server | Out-File -Append $masterLog
}

I ended up making the entire foreach a variable by begining the script with: $out = Foreach{.......}. I then piped the variable at the end

$out | Out-File $logfile

Here is a sample:

$out = foreach($server in $servers){
    invoke-command -cn $server -scriptblock {
        Param($server)
        "{0} :Begin DLL registration for {1}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"),$server
    } -ArgumentList $server
}

$out | Out-File $logfile
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!