I have a folder that does not contain any files with the extension "rar". I run the following from the PowerShell commandline using gci (alias of Get-ChildItem):
PS> gci *.rar
As expected, nothing is reported back since no such files exist. But when I do an "echo $?"
, it returns true.
How can I test the non-existence of files for a given file extension? I am using PowerShell v2 on Windows 7.
#If no rar files found...
if (!(gci c:\ *.rar)){
"No rar files!"
}
#If rar files found...
if (gci c:\ *.rar){
"Found rar file(s)!"
}
'if' evaluates the condition specified between the parentheses, this returns a boolean (True or False), the code between the curly braces executes if the condition returns true. In this instance if gci returns 0 files that would return False (perhaps equivalent to 'if exists') so in the first example we use the not operator (!) to essentially inverse the logic to return a True and execute the code block. In the second example we're looking for the existence of rar files and want the code block to execute if it finds any.
gci returns an array. You can check how many results are in the array.
if ((gci *.rar | measure-object).count -eq 0)
{
"No rars"
}
With PowerShell v3 it's a bit easier:
if ((gci *.rar).Count -eq 0)
{
"No rars"
}
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