Reputation: 909
I am wondering if the Try / Catch
below works or should I use an IF ($problem)
instead of the Try/Catch
Try {
New-Item -Path C:\reports -ItemType Directory -ErrorAction SilentlyContinue -ErrorVariable Problem -Force
}
Catch {
Write-Warning "Problem with C:\Report directory. Unable to create report $Type of $SourceEmail $Flag $DestinationEmail"
}
I am checking to see if a directory exists and if not attempt to create the directory.
I am not sure if because I am using -ErrorAction SilentlyContinue -ErrorVariable Problem
the try/catch
is not working as intended?
Altenative
New-Item -Path C:\reports -ItemType Directory -ErrorAction SilentlyContinue -ErrorVariable Problem -Force
If ($Problem) {
Write-Warning "Problem trying to create C:\Reports."
}
Upvotes: 2
Views: 1652
Reputation: 437478
I am checking to see if a directory exists and if not attempt to create the directory.
New-Item
's -Force
switch can be used to create a directory unless it already exists; a System.IO.DirectoryInfo
object describing either the preexisting directory or the newly created directory is returned (note that -Force
also creates parent directories on demand).
Since you're already using -Force
, this means that only a true error condition is reported, such as a lack of permissions.
In the simplest case, you can simply abort your script when such an error condition occurs, using -ErrorAction Stop
to convert the (first) non-terminating error that New-Item
reports to a script-terminating one:
$targetDir = New-Item -Force -ErrorAction Stop -Path C:\reports -ItemType Directory
If an error occurs, it will be printed, and the script will be aborted.
If you want to capture errors and perform custom actions, you have two mutually exclusive options:
$Problem
, via -ErrorVariable Problem
, and act on the value of $Problem
afterwards; -ErrorAction SilentlyContinue
suppresses display of the error:[1]$targetDir = New-Item -Force -ErrorAction SilentlyContinue -ErrorVariable Problem -Path C:\reports -ItemType Directory
if ($Problem) {
Write-Warning "Problem trying to create C:\Reports: $Problem"
# Exit here, if needed.
exit 1
}
-ErrorAction Stop
and use a try { ... } catch { ... }
statement to catch it, in whose catch
block $_
refers to the error at hand:try {
$targetDir = New-Item -Force -ErrorAction Stop -Path C:\reports -ItemType Directory
} catch {
$Problem = $_
Write-Warning "Problem trying to create C:\Reports: $Problem"
# Exit here, if needed.
exit 1
}
For a comprehensive overview of PowerShell's surprisingly complex error handling, see this GitHub docs issue.
[1] This makes the capturing of the error via -ErrorVariable
silent; do not use -ErrorAction Ignore
, as that will render -ErrorVariable
ineffective.
Upvotes: 5