In this scenario, there two servers. We'll call them ServerA and ServerB. There is also network share: \\share-ip-address\hidden_share$.
I am using the following Powershell command to get the most recent file name and date:
$CurrentPath = '\\share-ip-address\hidden_share$\sub-folder\';
Get-ChildItem -LiteralPath $CurrentPath -Filter "*string*.ext" -Recurse | Sort-Object LastWriteTime | Select-Object Name, LastWriteTime -Last 1;
For proximity/performance reasons, I want to run this command on ServerB, but the job scheduling mechanism resides on ServerA. My plan was to run the following command from ServerA:
$CurrentPath = '\\share-ip-address\hidden_share$\sub-folder\';
Invoke-Command -ComputerName ServerB -Script {Get-ChildItem -LiteralPath $using:CurrentPath -Filter "*string*.ext" -Recurse | Sort-Object LastWriteTime | Select-Object Name, LastWriteTime -Last 1};
Running the script inside of Invoke-Command from ServerA returns an error:
Cannot find path '\\share-ip-address\hidden_share$\sub-folder\' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\share-ip-...$\sub-folder\:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
+ PSComputerName : ServerB
However, I can successfully run the original script block (outside of Invoke-Command) directly from ServerB while logged in as the same domain account. I can also successfully run the script within the Invoke-Command context directly from ServerB by eliminating the -ComputerName parameter and the using: prefix on the variable name (ie, $CurrentPath instead of $using:CurrentPath).
I have tried calling the code from ServerA using a path that is local to ServerB, such as C:\windows\system32\drivers\etc, and it works as expected, so remoting appears to be functional. It seems that some aspect of security is being handled differently when calling Invoke-Command for a remote computer, but I have been unable to isolate the problem.
I have also tried different network shares with the same results, so I don't think the problem is specific to the target share.
2 Answers 2
Could you run this on ServerA
Invoke-Command -ComputerName ServerB -Script {write-output $using:CurrentPath};
... to see if the variable passes correctly?
You could try another way of passing the variable. Like this, for example:
Invoke-Command -ComputerName ServerB -ArgumentList $CurrentPath -ScriptBlock {
param($path)
Get-ChildItem -LiteralPath $path -Filter "*string*.ext" -Recurse | Sort-Object LastWriteTime | Select-Object Name, LastWriteTime -Last 1
}
1 Comment
Thanks to mklement0 for pointing out the double-hop issue, which I had not considered. I believe that is the most likely root cause of the problem, for which I will have to come up with a workaround.
(Get-CimInstance -ClassName Win32_Share | Where-Object Name -eq 'hidden_share$').Pathto find out the location on ServerB.