In my powershell script I have the following line:
$DirectoryInfo = Get-ChildItem $PathLog | Where-Object { $_.PSIsContainer }
to read some data from the path given in the variable $PathLog. But I realizes that even if the Get-ChildItem command failed (for example, the given path in $PathLog does not exist), and an error is written to the shell, the script continues.
How can I check if this Get-ChildItem was successfull? I want to use it to trigger an if clause as follows which stops the script at that moment:
if (???) {
"There was an error"
return
}
What to put into the brackets? How how to do it otherwise?
A "light-weight" alternative to try/catch/finally is the $? automatic variable. If the previous command failed, it'll have a value of $false:
Get-ChildItem F:\non\existing\path -ErrorAction SilentlyContinue
if(-not $?)
{
throw "Get-ChildItem failed"
}
You can use a Try/Catch block to catch the error like @Beatcracker answered or if you really just care if it succeeeded or not, you can use $?.
$?
Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.
Source: about_Automatic_Variables
When using $? I usually hide the error from Get-ChildItem too, so I've added -ErrorAction SilentlyContinue to do that in the sample.
$DirectoryInfo = Get-ChildItem c:\DoesntExist -ErrorAction SilentlyContinue | Where-Object { $_.PSIsContainer }
if($?) {
"It worked!"
} else {
"It failed! :-("
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With