Просто несколько мыслей здесь, и не совсем понятно, почему вы ориентируетесь на VMId, но это выбор.
Я просто вызываю вещи динамически, чтобы избежать, ну, вы знаете ...
$HyperVServerName = $env:COMPUTERNAME
$VMName = (Get-VM)[3].Name
$creds = Get-Credential -Credential "$env:USERDOMAIN\$env:USERNAME"
# I am using variable squeezing to assign and output info. In prod you'd remove those parens.
($VMID = (Get-VM -ComputerName $HyperVServerName -Name $VMName).ID)
<#
When it comes to PSRemotig, it's one or the other
- Implicit = New-PSSession - remote command stuff - Invoke-Command, etc...
- Explicit = Enter-PSSssion - user ineractive stuff
they cannot be use on the same target at the same time, it's redundant.
Also, the $VMID would never be not null, becasue you are directly populating it above.
#>
If(-Not ($VMID -eq $null))
{
<#
There is going to be an Implicit PSRemoting session when you do this
You can see this, if you output the info as you call it. Well, in testing.
I am using variable squeezing to assign and output info. In prod you'd remove those parens.
#>
($psSession = New-PSSession -VMId $VMID -Credential $creds)
<#
So this is moot. The session wll never be -Not null, becasue of the previous command,
Unless the session connection failed, then you should be catching that error anyway.
so, don't do this Explicit command, if you are directly setting an Implicit one.
Even in your code below, it's still moot, as you are trying to use that $pssession
which does not exist, via the ENter-PSSession.
So, if $pssession is null, the Enter-PSSEssion is also moot.
#>
<#
If(-Not ($psSession -eq $null))
{
Enter-PSSession -Session $psSession
#Do some stuff here...
}
#>
}
# So, you code could be something like.
$HyperVServerName = "TheServerName"
$VMName = "AValidVMName"
$SnapshotName = "ASnapshotName"
$creds = Get-Credential
Restore-VMSnapshot -ComputerName $HyperVServerName -VMName $VMName -Name $SnapshotName -Confirm:$false
Start-VM -ComputerName $HyperVServerName -Name $VMName
#Do some checks to make sure the VM is running...
($VMHost = Get-VM -ComputerName $HyperVServerName -Name $VMName)
Try
{
($psSession = New-PSSession -VMId $VMHost.Name -Credential $creds)
# Do some stuff here
}
Catch
{
Write-Warning -Message "Error calling the implicit remote session for $($VMHost.Name). Starting explicit session for $($VMHost.Name)."
$Error | Format-List -Force | Out-String | clip | notepad
Start-Sleep -Seconds 1
[void][reflection.assembly]::loadwithpartialname("system.windows.forms")
[system.windows.forms.sendkeys]::SendWait('^v')
Enter-PSSession -ComputerName $($VMHost.Name) -Credential $creds
#Do some stuff here...
}