2

I'm creating a small script which will list EXE files on the computer.

$computername = get-content env:computername
get-childitem C: -recurse | ? {$_.fullname -notmatch 'C:\\Windows'} | where {$_.extension -eq ".exe"} | format-table fullname | Out-File "\\server\incomming\$computername.txt"

The problem is that -notmatch doesn't accept more statements. I could copy-paste ? {$_.fullname -notmatch 'C:\\Windows'} and use for other folders like Program Files (x86), Program Files and so on. But I wouldn't like to bloat a script too much.

Is there a way I could exclude numerous folders with -notmatch statement?

3 Answers 3

6

You can use the logical operators like -and for more complex logical expressions.

Get-ChildItem C:\ -Recurse | Where-Object { ($_.FullName -notmatch "C:\\Windows") -and ($_.FullName -notmatch "C:\\Program Files") }   

For many paths, I'd add them to an array or a hash table before calling Get-ChildItem and use Where-Object check if the pipeline file object path is present in the array or hash table. Eventually, you have to list the paths somewhere, but not necessarily in a single command. For example:

$excludedPaths = @("C:\Windows", "C:\Program Files");
Get-ChildItem C:\ -Recurse | Where-Object { $excludedPaths -notcontains $_.Directory }
1

Thanks for the answers!

And is it possible to get output longer than it is now?

It is now something like 100 symbols and then it ends with dots if path is longer than that. I've get something like this - C:\my files\my programs\prog...

1
  • PowerShell does this to make the output readable in table formatting. You can always save the results to a file (e.g. | Export-Csv), or use | Format-List which will break lines instead of adding ellipses. | Select-Object -Property FullName | Format-List will return just the file names.
    – PeterK
    Oct 16, 2014 at 5:39
0

I would use something like this:

get-childitem -literalpath e:\*.exe -Recurse | where { $_.DirectoryName -notmatch "Windows" -and $_.DirectoryName -notmatch "MyOtherFiles"}
2
  • $_.DirectoryName is no good, you would still get matches for files in eg. \Windows\System32 Oct 13, 2014 at 9:53
  • DirectoryName is just the item folder in String format, if you want to be precise you want to replace the -notmatch with -ne and spell out the folder name, i.e. $_.DirectoryName -ne "e:\windows" Oct 13, 2014 at 10:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.