Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 534
Sabuncu Avatar asked Jan 13 '23 06:01

Sabuncu


2 Answers

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

like image 141
nimizen Avatar answered Jan 22 '23 21:01

nimizen


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"
}
like image 23
Lars Truijens Avatar answered Jan 22 '23 21:01

Lars Truijens