Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check in powershell if Get-ChildItem has failed?

Tags:

powershell

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?

like image 433
Alex Avatar asked Dec 11 '25 03:12

Alex


2 Answers

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"
}
like image 72
Mathias R. Jessen Avatar answered Dec 14 '25 08:12

Mathias R. Jessen


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! :-("
}
like image 21
Frode F. Avatar answered Dec 14 '25 08:12

Frode F.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!