Reputation: 1435
I've seen responses using Get-ChildItem for searching for a file but so far I haven't seen a way of turning the object result into a string that I can use.
The overall problem is that there is an exe that is consistently named within the local appdata of multiple pcs but the path uses a hash in a parent folder. I want to be able to run the file via powershell but since I can't know what the parent folder name is, I have to do a search, return the path name, and then run the file as part of that path.
Upvotes: 0
Views: 2443
Reputation: 16266
One thing to take care about is if there might be multiple like-named files under the directory point. If there are multiple files, you have to make a decision about what to do in that case.
This will get the file instances into an array. The first one can be referenced at index 0. This code fragment will use the first one and keep going. That might not be what you want to do.
$file = @(,Get-ChildItem -Path $Env:LOCALAPPDATA -Recurse -Include thefile.exe)
if ($file) {
$thedir = $file[0].DirectoryName
} else {
# handle error case
}
Upvotes: 0
Reputation: 29470
The object returned from Get-ChildItem
is a a FileInfo
object with many properties you can query. So you can store the result in a variable:
$file = Get-ChildItem $env:APPDATA -Recurse -Include yourfilename.ext
You can then query the parent directory using the Directory
property:
$file.Directory
Upvotes: 3