Reputation: 1
Get-ChildItem gets an error when the path is a variable
This works:
PS D:\DMH> Get-ChildItem -Path '\\MHRZRSEFS501\F$\NewSkies FileShares\FRBatch$\Test\Test.txt'
Directory: \\MHRZRSEFS501\F$\NewSkies FileShares\FRBatch$\Test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 5/19/2019 2:45 AM 18 Test.txt
But if I put the Path into a variable it doesn't work:
PS D:\DMH> $SPath = "'\\MHRZRSEFS501\F$\NewSkies FileShares\FRBatch$\Test\Test.txt'"
Get-ChildItem -Path $SPath
Write-Host "SPath =$SPath"
Get-ChildItem : Cannot find path 'D:\DMH\'\MHRZRSEFS501\F$\NewSkies FileShares\FRBatch$\Test\Test.txt'' because it does not exist.
***
SPath ='\\MHRZRSEFS501\F$\NewSkies FileShares\FRBatch$\Test\Test.txt'
D:\DMH\
is obviously the directory where I launched PowerShell
from but how did it get in the path for the command?
Upvotes: 0
Views: 2935
Reputation: 649
This was an absolute nightmare, get-childitem cannot except a string variable if there are multiple paths. Use an array instead.
Get-ChildItem -Path "\server1\c$\temp", "\server1\d$\temp" -File -recurse # works
$path = '"\server1\c$\temp", "\server1\d$\temp"'; Get-ChildItem -Path "\server1\c$\temp", "\server1\d$\temp" -File -recurse # fails with cannot find path
$path = "'"\server1\c$\temp", "\server1\d$\temp'""; Get-ChildItem -Path "\server1\c$\temp", "\server1\d$\temp" -File -recurse # fails with illegal character message (the tick)
Any string that has multiple paths fails, however an array with += as shown below will work.
$servers = @("server1", "server2");
$partialPaths = @("\c$\temp\", "\d$\temp\");
foreach ($server in $servers)
{
$paths = @();
foreach ($partialPath in $partialPaths)
{
$paths += "\\" + $server + $partialPath;
}
}
Get-ChildItem -Path $paths -File -recurse;
Upvotes: 0
Reputation: 17472
Double quote ask to PowerShell to evaluate the string. Try this (without double quote):
$SPath = '\\MHRZRSEFS501\F$\NewSkies FileShares\FRBatch$\Test\Test.txt'
Upvotes: 1