2

I have valid credentials of a Windows service account stored in $creds and want to use them to access the C:\temp\ directory on another server called remotehost. I use Invoke-Command to execute the same test twice, first on localhost (which leads to denied access) and then on remotehost (which succeeds):

Invoke-Command -ComputerName localhost -Credential $creds -ScriptBlock {
    Test-Path -Path \\remotehost\C$\temp\    # access denied
}

Invoke-Command -ComputerName remotehost -Credential $creds -ScriptBlock {
    Test-Path -Path \\remotehost\C$\temp\    # True
}

Can anyone explain this "access denied"? Why can I successfully connect to remotehost and execute a command there, but I cannot execute the same command from localhost directly?

Just to be sure, I also verified that the connection to localhost works:

Invoke-Command -ComputerName localhost -Credential $creds -ScriptBlock {
    Test-Path -Path C:\temp    # True
}
3
  • 1
    You have to be admin on localhost. Commented Aug 12, 2024 at 16:55
  • I am in the Administrators group and the service account is, too. Anyway, how would that explain the access denied in one case but not the other? Commented Aug 12, 2024 at 18:31
  • as in right click on powershell and "run as administrator" Commented Aug 12, 2024 at 18:39

2 Answers 2

2

What you're experiencing is the double hop issue. You are running a remote command and trying to make another hop to a different remote system. Even though it is your local system, it is still a remote session and thus has the same limitations. You can confirm this by using your remotehost example with a 3rd remote location.

Invoke-Command -ComputerName remotehost1 -Credential $creds -ScriptBlock {
    Test-Path -Path \\remotehost2\C$\temp\
}

You will also get Access Denied

enter image description here

My guess for why this example succeeds is windows is smart enough to know the UNC path actually points at the local system.

Invoke-Command -ComputerName remotehost1 -Credential $creds -ScriptBlock {
    Test-Path -Path \\remotehost1\C$\temp\
}
Sign up to request clarification or add additional context in comments.

Comments

-1

Why are you using the network path inside the ScriptBlock? When you use Invoke-Command with a -ComputerName, the command runs on the remote computer, so referencing \remotehost1\C$\temp\ (a network path) within the script block may not be necessary. Instead, you can directly use the local path C:\temp\ within the remote session.

Invoke-Command -ComputerName remotehost -Credential $creds -ScriptBlock {
Test-Path -Path 'C:\temp\'}

2 Comments

I only did it like that for demonstration purposes.
Is it working now ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.