Почему я получаю сообщение об ошибке, что входной VMID не разрешается на одной виртуальной машине? - PullRequest
0 голосов
/ 30 мая 2019

Я использую PowerShell для подключения к виртуальной машине Hyper-V.Но по какой-то причине, когда я пытаюсь запустить PSSession, я получаю сообщение об ошибке " Входной VMID не разрешается в одну виртуальную машину. "

Код выглядит следующим образом:

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

$VMID = (Get-VM -ComputerName $HyperVServerName -Name $VMName).ID

If(-Not ($VMID -eq $null))
{
    $psSession = New-PSSession -VMId $VMID -Credential $creds
    If(-Not ($psSession -eq $null))
    {
        Enter-PSSession -Session $psSession
        #Do some stuff here...
    }
}

Я получаю сообщение об ошибке $psSession = New-PSSession -VMId $VMID -Credential $creds.

Дополнительные сведения об ошибке:

  • CategoryInfo: InvalidArgument (:) [New-PSSession], ArgumentException
  • FullyQualifiedErrorId: InvalidVMIdNotSingle, Microsoft.PowerShell.Commands.NewPSSessionCommand

Есть какие-либо идеи о том, что вызывает эту ошибку, и как я могу ее исправить?


Я уже мог запускать команды на ВМ, но я пытался изменитькод, чтобы мне не пришлось указывать имя хоста виртуальной машины при использовании Invoke-Command.

1 Ответ

1 голос
/ 31 мая 2019

Просто несколько мыслей здесь, и не совсем понятно, почему вы ориентируетесь на 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...
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...