Error Logging

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Chris Bakker Chris Bakker 1 month ago.

  • Author
  • #71509
    Profile photo of Ted Chen
    Ted Chen

    How do you cause all errors to be written to a file? I have the following script:

    function Create-Directory{
    [String]$InputFile = [Environment]::GetFolderPath("Desktop") + "\DirectoryList.csv",
    [String]$ErrorLog = [Environment]::GetFolderPath("Desktop") + "DirectoryError.txt"
    Import-Csv -Path $InputFile | ForEach-Object {
        Try { New-Item -ItemType Directory -Path $_.NewPath -ErrorAction Stop }
        Catch { $_ | Out-file $ErrorLog -Append }

    And the input file DirectoryList.csv looks like this:

    The last entry will surly cause an error because there is no A:\ on the PC. But when I run the script by typing the function name 'Create-Directory', the file that is meant to trap error 'DirectoryError.txt' is not created.

    Originally I have my script like this:

    Import-Csv -Path "C:\Users\thchen\Desktop\DirectoryList.csv" | ForEach-Object {New-Item -ItemType Directory -Path $_.NewPath} -ErrorAction SilentlyContinue -ErrorVariable e | out-file C:\users\thchen\desktop\logfile.txt

    The script above produced the file 'logfile.txt' but there is nothing inside. So, how should error be trapped and written into a file?

    Thanks for any help.

  • #71510
    Profile photo of Ted Chen
    Ted Chen

    I found the error and feel like a complete idiot. If I change the line
    [String]$ErrorLog = [Environment]::GetFolderPath("Desktop") + "DirectoryError.txt"
    [String]$ErrorLog = [Environment]::GetFolderPath("Desktop") + "\DirectoryError.txt"

    Then the function works just fine. Thanks!

    • #71588
      Profile photo of Chris Bakker
      Chris Bakker

      This work (nearly) always and you dont have to worry about the slash.
      Join path wil figure that out for you.

      join-path ([Environment]::GetFolderPath("Desktop")) "DirectoryList.csv"

You must be logged in to reply to this topic.