0

Afternoon!

EDIT

After some more troubleshooting, I've noticed it doesn't seem to want to catch the error from the New-Item -ItemType Directory -Path Z:\PMO\PMOBits\test section. If I put in a Null value, it catches that error in both my Get-Logger function and using Write-output. Why wouldn't it catch the Folder already exists error?

I'm have a logging function in my PowerShell script and I'm trying to incorporate some error handling using this function. Below is the logging function.

Function Get-Logger { 
    param(
       [Parameter(Mandatory=$true)]
       [String]$message,
       [Parameter(Mandatory=$false)]
       [validatescript({[enum]::getvalues([system.consolecolor]) -contains $_})][string]$Color
    )

    $TimeStamp = Get-Date -Format "MM-dd-yyy hh:mm:ss"

    Write-Host $TimeStamp -NoNewline
    IF ($Color) {
        Write-Host `t $message -ForegroundColor $($color)
    } Else {
        Write-Host `t $message -ForegroundColor Cyan
    }
    $logMessage = "[$TimeStamp]  $message"
    $logMessage | Out-File -Append -LiteralPath $VerboseLogFile
}

I'm testing this with some simple code for the error handling, see the test code below.

Try { New-Item -ItemType Directory -Path Z:\PMO\PMOBits\test } 
    Catch {
        Get-Logger "ERROR: This file already exists"
    }

When I run the script, I see the error populate on the terminal that it already exists, but It's not showing in my log file like the catch section should do.

I've also tried to catch the error without using my function below:

try{...}
catch {
Write-Output $_ | Out-File -Append -LiteralPath $VerboseLogFile
}
Fitzgery
  • 558
  • 5
  • 14

1 Answers1

2

Add the -ErrorAction Stop with your New-Item statement.

    Try { New-Item -ItemType Directory -Path Z:\PMO\PMOBits\test -ErrorAction Stop } 
    Catch {
        Get-Logger "ERROR: This file already exists"
    }
Jawad
  • 11,028
  • 3
  • 24
  • 37
  • 1
    @Fitzgery, see [this answer](https://stackoverflow.com/a/59641995/45375) for background information; Jawad, variations of this problem keep coming up, and I encourage you to vote for closure as a duplicate in the future. – mklement0 Mar 11 '20 at 21:03