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
    Posts
  • #71509
    Profile photo of Ted Chen
    Ted Chen
    Participant

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

    function Create-Directory{
    param(
    [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:
    NewPath
    C:\Users\thchen\Desktop\TedTest1\TedTest2\TedTest3
    C:\Users\thchen\Desktop\TedMoreTest\TedMoreTest2
    A:\Test\MoreTest

    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
    Participant

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

    Then the function works just fine. Thanks!

    • #71588
      Profile photo of Chris Bakker
      Chris Bakker
      Participant

      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.