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!