用户未登录时不执行Invoke-Command

时间:2017-04-26 07:30:45

标签: powershell powershell-remoting

我的目标是重置VM并在其上运行一些安装程序。这就是我的工作:

Write-Host "Revert VM to snapshot"
Get-VM -Name $vmName | Restore-VMSnapshot -Name "7Zip" -Confirm:$false

Write-Host "Start VM"
Get-VM -Name $vmName | Start-VM

Write-Host "Wait for VM to be ready"
Wait-VM $vmName
Write-Host "Wait a little bit more..."
Start-Sleep -Seconds 20

Write-Host "Create credetials"
$computer = "W7P-MY-COMPUT"
$username = $computer + "\localadmin"
$password = cat C:\build\mysecurestring.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential `
     -argumentlist $username, $password

Write-Host "Invoke remote script"
Invoke-Command -ComputerName $computer -FilePath c:\build\GetInstallers.ps1 -Credential $cred

引用的脚本会下载一些msi文件并安装它们。如果我运行所有VM命令,手动登录计算机然后执行Invoke-Command,这一切都可以正常工作。

但是一下子跑完就给了我这个输出:

Revert VM to snapshot
Start VM
Wait for VM to be ready
Wait a little bit more...
Create credetials
Invoke remote script
[W7P-SAMOS-WEB-I] Connecting to remote server W7P-SAMOS-WEB-I failed with the following error message : WinRM cannot complete the operation. Verify that the 
specified computer name is valid, that the computer is accessible over the network, and that a firewall exception for the WinRM service is enabled and allows 
access from this computer. By default, the WinRM firewall exception for public profiles limits access to remote computers within the same local subnet. For 
more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo          : OpenError: (W7P-SAMOS-WEB-I:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionStateBroken

3 个答案:

答案 0 :(得分:1)

检查服务状态。确保它正常运行

get-service winrm

要启用PS远程处理,请使用:

Enable-PSRemoting –force

将系统添加到可信主机列表中:

winrm s winrm/config/client '@{TrustedHosts="RemoteComputer"}'

验证它:

winrm quickconfig

完成后,从源到目的地运行invoke-command并查看结果。如果出现错误,请发布。

除了该请求之外,您还要仔细检查防火墙并确保它已被禁用。

或接近这个:

Enable-PSRemoting -SkipNetworkProfileCheck -Force
Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any

答案 1 :(得分:0)

根据您的VM的操作系统版本,可能未配置WinRM,您应该在Windows Server 2012及更高版本上正常运行,仍然值得检查它已启用。然后,您可以在此处查看讨论:Invoke-Command failed: WinRM cannot complete the operation,其中涉及Ranadip在评论中提到的要点。

答案 2 :(得分:0)

当我尝试做Invoke-Command时,winrm服务还没有运行。使用Start-Sleep命令等待更长时间(约3-4分钟)修复了问题。