问题
I need to execute powershell script on remote computer with admin privilegies. I have 2 scripts: client and server. When i start client.ps1 i invoke command on server machine but get access error. I get no error if I use simple code in server.ps1 like write-host "hello".
server.ps1:
Get-service -ComputerName 'client'
client.ps1:
$ScriptBlockContent = {
d:\server.ps1
}
$remote=New-PSSession -ComputerName 'server'
Invoke-Command $remote -ScriptBlock $ScriptBlockContent
回答1:
Your problem is authentication. You have to enable the server to use your credentials for that. You can do this by using CredSSP
.
Enable this on your client:
Enable-WSManCredSSP -Role Client -DelegateComputer ServerNameHere
Enable it on your server:
Enable-WSManCredSSP -Role Server
Now add this to your
Invoke-Command
:
-Credential Domain\YourUsername -Authentication CredSSP
A remark on that: With CredSSP, its easy to steal your credentials, if you connect to a compromised system (same as RDP). Be sure that you do this on secure computers only.
回答2:
Your client is trying to open D:\server.ps1 and getting access denied. Your script block doesn't even contain the neccesary code to cause powershell to process the contents of the server.ps1 anyway. You have it way to complicated.
You need to properly define a script block:
$scriptblock = { Get-service -ComputerName 'client' }
$remote=New-PSSession -ComputerName 'server'
Invoke-Command $remote -ScriptBlock $scriptblock
Running this command will connect to the machine called 'Server'
and tell it to run Get-Service
on 'Client'
You don't need a client.ps1
and server.ps1
It can all be done from 1 script.
You also need to ensure winrm
is running and configured on the server.
来源:https://stackoverflow.com/questions/43968015/run-ps1-on-remote-machine