I am trying to use powershell to update some programs for my company. I am writing a script to do so (as instructed). When I install the new version of the program on the machines, it also requires me to 'upgrade' existing folders to match the new version of the software. I need to find all of the folders that contain a certain hidden folder(let the name of said folder be .blah). I am trying to use the get-childitem command, with -path [drives to check] -Recurse -Directory -Force -EA SilentlyContinue. However, I am not sure how to filter correctly to only find folders that contain the .blah folder inside of it. Help would be very much appreciated.
-
1seems like `-Filter *blah` is what you're looking for – Santiago Squarzon Jun 22 '22 at 22:57
1 Answers
Combine your Get-ChildItem call with a Where-Object call that tests for a child directory of a given name using Test-Path:
# Note: "." refers to the *current* directory
# Adjust as needed.
Get-ChildItem -LiteralPath . -Recurse -Directory -Force -ErrorAction Ignore |
Where-Object {
Test-Path -ItemType Container -LiteralPath "$($_.FullName)\.blah"
}
The
Get-ChildItemcall outputs all directories (-Directory) in the entire directory subtree (-Recurse), including hidden ones (-Force), ignoring any errors (such as from lack of permissions,-ErrorAction Ignore).The
Where-Objectcall callsTest-Pathto look for a.blahchild directory (-ItemType Container) in the directory at hand ($_).With a
-LiteralPathargument,Test-Pathfinds the specified path if it exists, irrespective of whether the target file or directory is hidden.- By contrast, with a wildcard-based
-Pathargument, hidden items are not found, and given that, as of PowerShell 7.2.5,Test-Pathhas no-Forceswitch, there is no way to force their inclusion; this gap in functionality is the subject of GitHub issue #6501.
- By contrast, with a wildcard-based
Note: In PowerShell (Core) 7+, you could simplify
"$($_.FullName)\.blah"to"$_\.blah", because the[System.IO.DirectoryInfo]and[System.IO.FileInfo]instances output byGet-ChildItemandGet-Itemthere consistently stringify to their full path (.FullName) property, unlike in WindowsPowerShell, where they situationally stringify by their file/directory name only - see this answer.
- 382,024
- 64
- 607
- 775