Sabuncu
Sabuncu

Reputation: 5264

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

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.

Upvotes: 4

Views: 3281

Answers (2)

nimizen
nimizen

Reputation: 3419

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

Upvotes: 6

Lars Truijens
Lars Truijens

Reputation: 43595

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"
}

Upvotes: 3

Related Questions