Reputation: 148
How can I programmatically get the path to the file if it is in a sub directory?
Example:
main_dir
|
sub_main_dir
|
another_sub
|
File
I want to grab the directory to the file and invoke it, I know how to invoke the file with Invoke-Item
but what I need is the directory that the file is in, in order to invoke it correctly:
function search_for_file($directory, $fileName){
if (search_dir($directory) -contains $fileName){
say("Package found. Invoking package, follow the steps in the setup wizard.")
invoke $fileName
} Else {
say("Did not find package, check spelling and try again")
}
}
Error:
Invoke-Item : Cannot find path 'C:\dev\testfiles MOCK_DATA_XCL.xlsx\' because
it does not exist
Upvotes: 0
Views: 56
Reputation: 7029
This will search $directory
and its subdirectories for the first $fileName
it finds and then invoke it.
Get-ChildItem -Path $directory -Recurse -Filter $fileName `
| Select-Object -First 1 -ExpandProperty FullName `
| Foreach-Object { Invoke-Item $_ }
Response to comment
If you just want to get the path to the file then you can simply remove the last pipe and assign the result to a variable:
$path =
Get-ChildItem -Path $directory -Recurse -Filter $fileName `
| Select-Object -First 1 -ExpandProperty FullName
Upvotes: 1