Run .ps1 on remote machine

依然范特西╮ 提交于 2019-12-12 19:08:05

问题


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.

  1. Enable this on your client:

    Enable-WSManCredSSP -Role Client -DelegateComputer ServerNameHere

  2. Enable it on your server:

    Enable-WSManCredSSP -Role Server

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!