alroc's helpful answer explains the problem well and points to resources for solving it through prior configuration.
- An explanation of the underlying problem, the infamous Kerberos double-hop problem, as well as an overview of available solutions can be found in this blog post.
As for an ad hoc solution for accessing a network share in a remote session (PSv3+):
Pass the credentials for the session via a variable; e.g., -Credential $cred
Then use these credentials inside the session too - e.g., as $using:cred
- to establish a session-scoped auxiliary drive that maps the network location, using New-PSDrive
.
Once the drive has been mapped, the target location is accessible - whether via the drive name, or directly by UNC path.
Note: This is a variation of the approach discovered by the OP him/herself and discussed briefly in a comment on alroc's answer, except that New-PSDrive
is used rather than net use
, which obviates the need for retrieving the password as plain text.
The following sample code demonstrates running a script from a network share from inside a remote session:
# A sample script to run from a network share on a remote computer.
$script = '\\server-001\install\Install-Agent.ps1'
# A sample target computer.
$computer = 'ws-002'
# Obtain the credentials for the remote session and store them in a variable.
$cred = Get-Credential $env:USERNAME
Invoke-Command -ComputerName $computer -Credential $cred {
# Map the target network share as a dummy PS drive using the passed-through
# credentials.
# You may - but needn't - use this drive; the mere fact of having established
# a drive with valid credentials makes the network location accessible in the
# session, even with direct use of UNC paths.
$null = New-PSDrive -Credential $using:cred -Name dummy -Root (Split-Path -Parent $using:script) -PSProvider FileSystem
# Invoke the script via its UNC path.
& $using:script
}
Note:
$null = ...
suppresses New-PSDrive
's output (it outputs an object describing the newly created drive).
Since the drives created by New-PSDrive
are not persistent (except if you pass -Persist
), there's no need to explicitly remove the dummy drive again, but you can do so with Remove-PSDrive
.
- Also note that PS drive definitions are scoped so that only the calling scope and its descendants see the drive; this enables wrapping statements in
& { ... }
to call them in a child scope, which means the a PS drive created inside that block will automatically go out of scope when the block is exited.