Question:
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):
1 2 |
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.
Answer:
1 2 3 4 5 6 7 8 9 |
#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.