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
}