Determine if files with a certain file extension are not in the folder using PowerShell

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):

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:


‘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.

Source:

Determine if files with a certain file extension are not in the folder using PowerShell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply