title: How to Log Errors in Powershell?
body: <p>[1] I am trying to create Error logs for my PowerShell script. I need to create a function so that instead of using Write-Host I can directly call that function and whatever the error I am getting in the Script can be directly logged into the Log File.
  [2] I have used the following method but it doesn't seem that will work for every PowerShell script.</p>
  <pre><code>function WriteLog
  {
      Param ([string]$LogString)
      $LogFile = &quot;C:\$(gc env:computername).log&quot;
      $DateTime = &quot;[{0:MM/dd/yy} {0:HH:mm:ss}]&quot; -f (Get-Date)
      $LogMessage = &quot;$Datetime $LogString&quot;
      Add-content $LogFile -value $LogMessage
  }
  
  WriteLog &quot;This is my log message&quot;
  </code></pre>
  <p>[3] Can Anyone Suggest a more easy way to handle logging of Error into the file?</p>