Search code examples
powershellpowershell-remoting

Invoke-Command not executed when user not logged in


My goal is to reset a VM and run some installers on it. This is what I do:

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

The script that is referenced downloads some msi files and installs them. All this works fine if I run all the VM commands, log into the computer manually and then execute the Invoke-Command.

But running all at once gives me this output:

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

Solution

  • The winrm service was not running yet when I tried to do Invoke-Command. Waiting longer using the Start-Sleep command (approx 3-4 min) fixed the issue.