In PowerShell, forward credential to a program o remoted server.

Hua Wang 1 Reputation point
2020-11-04T15:30:03.717+00:00

I am trying to use PowerShell from my desktop to remote to a sever and run a program there. But the job failed when the program tried to read/write a txt file from another server. The error message is 'Insufficient Authorization'.

The code I am using is as following

$username = 'myusername'
$password = get-content C:\users\cred.txt
$secureStringPwd = ConvertTo-SecureString $password -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ($username, $secureStringPwd)

Invoke-Command -ComputerName server1 -Credential $creds -ScriptBlock {
& 'F:\batchfiles\test.cmd'
}

I searched looks like it is the second hop problem. I looked through the following doc
https://learn.microsoft.com/en-us/powershell/scripting/learn/remoting/ps-remoting-second-hop?view=powershell-7

I modify the code to

$username = 'myusername'
$password = get-content C:\users\cred.txt
$secureStringPwd = ConvertTo-SecureString $password -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ($username, $secureStringPwd)

Invoke-Command -ComputerName server1 -Credential $creds -ScriptBlock {
Invoke-Command -ComputerName server2 -Credential $Using:creds -ScriptBlock {Get-ChildItem -Path
\server2\e$\data}
& 'F:\batchfiles\test.cmd'
}

The job did listed the files under \server2\e$\data\ with the PSComputerName as server1. But the cmd job still failed with the error of 'Insufficient Authorization'.

What I did wrong? How to pass my user credential into the cmd program?

Thanks!

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,363 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Vector BCO 131 Reputation points
    2020-11-04T21:24:28.077+00:00

    Hi

    I see 2 possible ways for your case:

    1. inside your second invoce-command you can copy all you need from remire server2 to remote server1. and rewrite your batch file for using files loccally instead of using some share
    2. rewrite your bat file to powershell and cover second hop inside with invoke-command/start-process/schedulled task or whatever else

    for now your 2nd hop still at the same place in first invoke-command in a bat file