title: Powershell logging from invoke-command
body: <p>I have a script that includes a function for logging.
  The function writes log to $msg variable then writes the message to the screen.
  i can redirect this output to a .txt file for logging.</p>
  
  <p>I need to run the script to multiple servers using invoke-command 
  and write the log output to a txt file on the computer running the script.</p>
  
  <p>I am trying to figure out how to output $msg in the write-log function from the PSSession and return it so I can create a master log file for all the servers.  Should I create and populate a custom object?  Not sure how to do that and get the results back from the remote session.</p>
  
  <p>Can this even be done?</p>
  
  <p>Here is an example of the code I am using and what the log file output should look like:</p>
  
  <pre><code>$servers = 'Server1','Server2'
  $logfile = 'c:\scripts\logs\Reg-DLL-log.txt'
  
  foreach($server in $servers){
      invoke-command -cn $server -sb{
          Param($server)
  
          Function write-log{
              [cmdletbinding()]
              Param(
                  [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [ValidateNotNullOrEmpty()]
                  [string] $Message,
                  [Parameter()] [ValidateSet(“Error”, “Warn”, “Info”)]
                  [string] $Level = “Info”,
                  [Parameter()] [ValidateRange(1,30)]
                  [Int16] $Indent = 0
              )
              $msg = "{0} {1}{2}:{3}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $Level.ToUpper(), (" " * $Indent), $Message
                  #This is output to screen
                  switch ($Level) {
                      'Error' { Write-Host ('{0}{1}' -f (" " * $Indent), $Message) -ForegroundColor 'Red'}
                      'Warn' { Write-Host ('{0}{1}' -f (" " * $Indent), $Message) -ForegroundColor 'Yellow'}
                      'Info' { Write-Host ('{0}{1}' -f (" " * $Indent), $Message) -ForegroundColor 'white'}
          }}
  
          write-log -message 'Begin DLL registration for $server' -level Info
          $RegFile = "cimwin32.dll"
          regsvr32 $RegFile /s
          write-log -message 'registered $RegFile' -level Info
          write-log -message 'End DLL registration for $server' -level Info
  
      } -ArgumentList $server
  }
  </code></pre>
  
  <p>Log output to Reg-DLL-log.txt should look like this:</p>
  
  <pre><code>2013-06-19 11:25:12 INFO:Begin DLL registration for Server1
  2013-06-19 11:25:12 INFO:registered cimwin32.dll
  2013-06-19 11:25:12 INFO:End DLL registration for Server1
  2013-06-19 11:25:12 INFO:Begin DLL registration for Server2
  2013-06-19 11:25:12 INFO:registered cimwin32.dll
  2013-06-19 11:25:12 INFO:End DLL registration for Server2
  </code></pre>