Reputation: 892
I want to match a string inside a file. If it matched, it will return the path of the file, if it is not matched it will return false. Using this code I can match and find the path if the string match, but if the string doesn't match it returns this error:
Get-Item : Cannot bind argument to parameter 'Path' because it is null.
$Path = "D:\190\Pro"
$SS = "1q1q"
$Paths = (Get-Item (Get-ChildItem "$Path\*\LST" | Select-String -Pattern "$SS").Path).Directory.FullName
if ($Paths) {
Write-Host "Found Path"
#Do next process
} else {
Write-Host "Not Found Path"
#Do next process
}
Upvotes: 0
Views: 212
Reputation: 200193
If Get-ChildItem | Select-String
doesn't produce a match you have an empty result in the nested expression. Passing that empty result to Get-Item
will essentially run Get-Item $null
, which throws the error you observed, because the -Path
parameter of that cmdlet doesn't accept $null
as an argument.
Replace the needlessly convoluted
$Paths = (Get-Item (Get-ChildItem "$Path\*\LST" | Select-String -Pattern "$SS").Path).Directory.FullName
with
$Paths = Get-ChildItem "$Path\*\LST" |
Where-Object { Select-String -Path $_.FullName -Pattern "$SS" } |
Select-Object -Expand DirectoryName
and the problem will disappear.
Upvotes: 1