尽管具有管理员权限,但无法使用 Powershell 关闭 HyperV VM

尽管具有管理员权限,但无法使用 Powershell 关闭 HyperV VM

我正在尝试使用一个脚本来关闭我的 Hyper-V VM,将其 VHD 复制到目标共享,然后重新启动它们。我发现spiceworks 上的脚本就在几天前。我总是收到错误,提示要关闭的系统名称是空值。

基本信息:

  • 我一直以管理员身份运行 powershell。
  • 我将 ExecutionPolicy 设置为“RemoteSigned”,以便执行本地 powershell 文件。
  • 我似乎正在运行 PowerShell v 2.0
  • 我在 Server 2008 R2 中运行 HyperV
  • 我正在虚拟机主机上直接执行此脚本

下面是脚本和我遇到错误的位置以及错误的具体内容的解释:

 $waitstart = 200
 $waitshutdown = 120


 if ($args[1] -match "0") {
 $inputfile=get-content $args[0]
 foreach ($guest in $inputfile) {
 write-host "Starting $guest"
 $vm = gwmi -namespace root\virtualization -query "select * from msvm_computersystem where elementname='$guest'"
 $result = $vm.requeststatechange(2)
 if ($result.returnvalue -match "0") {
 start-sleep -s $waitstart
 write-host ""
 write-host "$guest is started" -foregroundcolor green
 write-host ""
 }
 else {
 write-host ""
 write-host "unable to start $guest" -foregroundcolor red
 write-host ""
 }}}

 if ($args[1] -match "1") {
 $inputfile=get-content $args[0]
 foreach ($guest in $inputfile) {
 write-host "shutting down $guest"
 $vm = gwmi -namespace root\virtualization -query "select * from msvm_computersystem where elementname='$guest'"
 $vmname = $vm.name
 $vmshut = gwmi -namespace root\virtualization -query "SELECT * FROM Msvm_ShutdownComponent WHERE SystemName='$vmname'"
 $result = $vmshut.InitiateShutdown("$true","no comment")
 if ($result.returnvalue -match "0") {
 start-sleep -s $waitshutdown
 write-host ""
 write-host "no error while shutting down $guest"
 write-host "shutdown of $guest completed" -foregroundcolor green
 write-host ""}

 else {
 write-host ""
 write-host "unable to shutdown $guest" -foregroundcolor red
 write-host ""
 }}}

 else {
 write-host "USAGE: to shutdown VMs," -nonewline; write-host ".\managehyperV.ps1 c:\hosts.txt 1" -foregroundcolor yellow
 write-host "USAGE: to start VMs," -nonewline; write-host ".\managehyperV.ps1 c:\hosts.txt 0" -foregroundcolor yellow
 }

该脚本采用参数“1”或“0”来确定是否应关闭或启动“guests”文本列表中的虚拟机。

以管理员身份运行 Powershell 我可以成功运行以下查询:

 $vm = gwmi -namespace root\virtualization -query "select * from msvm_computersystem where elementname='$guest'"

这将返回某种代表虚拟机系统名称的字符串。

但是,以下查询总是返回空值:

 $vmshut = gwmi -namespace root\virtualization -query "SELECT * FROM Msvm_ShutdownComponent WHERE SystemName='$vmname'"

当我执行以下行时,似乎我的系统上不存在“Msvm_ShutdownComponent”类:

  $result = $vmshut.InitiateShutdown("$true","no comment")

我总是收到一条错误消息,指出“您无法对空值表达式调用方法”。我花了大约一天半的时间试图找出导致此问题的错误,但我无法缩小范围。

答案1

我已经创建了一个满足我需求的脚本,我将把它发布在这里。

此脚本执行以下任务:

  • 遍历所有列出的物理主机
  • 遍历所有未排除的虚拟机
  • 正常关闭虚拟机并等待关机完成
  • 对目标虚拟机的所有 VHD 文件(一次一个)执行同步 BITS 传输到指定位置
  • 传输完成后启动目标虚拟机

此脚本可以在远程物理主机上运行,​​无需在本地运行。请确保使用管理凭据运行该脚本,否则它将无法正常工作。

我正在使用 Windows Server 2008 R2,因此无法访问 Windows Server 2012 中提供的所有命令。

此外,这是“脚本小子”的终极表达;我把大约 4 个不同的脚本混合在一起,然后在其上添加了一些逻辑。请原谅语法等方面的不一致。

此脚本是从我使用的独立企业系统手动转录的,因此可能存在一些拼写错误。我还没有尝试直接执行此脚本。我的系统上的脚本似乎运行良好。

#Run this script in an administrative instance of powershell
#This script executes based on files in the C:\Scripts directory
cd "C:\Scripts"
#Import the BITS Library so that synchronous transfers can occur easily
Import-Module BitsTransfer
#Note that all these files are delimited by carriage returns - 1 host/vm name per line
#Place these files in the "C:\Scripts" directory on the system running this script

#HyperVParents is the list of remote systems that are hosting VMs that need backup.
$HyperVParents = Get-Content HyperV_Hosts.txt

#ExcludedVMs is the list of VMs that will not be turned off or booted during this process
#NOTE: All VM VHD files in Hyper-V are backed up with this script.
$ExcludedVMs = Get-Content ExcludedVMs.txt

#Build Date String
$filedate = get-date -format "M-d-yyyy"

#Create target directory on remote server for backup if it is not already present
#Replace REMOTESRV with your servername
$TargetPath = "\\REMOTESRV\VHDs\" + $filedate
If(!(Test-Path -Path $TargetPath))
    {
        New-Item -ItemType directory -Path $TargetPath
    }

Foreach ($HyperVParent in $HyperVParents)
{
$VMManagementService = Get-WmiObject -class "Msvm_VirtualSystemManagementService" -namespace "root\virtualization" -ComputerName $HyperVParent
$VMs = Get-WmiObject -Namespace "root\virtualization" -ComputerName $HyperVParent -Query "Select * From MSVM_ComputerSystem where Caption='Virtual Machine'"

Foreach ($VM in $VMs)
    {
    #Set $VMExcluded to null in order to test the next VM for exclusion
    #This routine could probably be more efficient.
    $VMExcluded = $null
    #Loop through list of excluded VMs to see if current VM is within this list
    Foreach ($ExcludedVM in $ExcludedVMs)
    {
        If ($VM.ElementName -eq $ExcludedVM)
        {
            $VMExcluded = $true
            Write-Host $VM.ElementName, ": Excluded from startup/shutdown process"
        }
    }

    $VMSettingData = Get-WmiObject -Namespace "root\virtualization" -Query "Associators of {$VM} Where ResultClass=Msvm_VirtualSystemSettingData AssocClass=Msvm_SettingsDefineState" -ComputerName $HyperVParent
    $VirtualDiskResource = Get-WmiObject -Namespace "root\virtualization" -Query "Associators of {$VMSettingData} Where ResultClass=Msvm_ResourceAllocationSettingData AssocClass=Msvm_VirtualSystemSettingDataComponent" -ComputerName $HyperVParent | Where-Object {$_.ResourceSubType -match "Microsoft Virtual Hard Disk"}
    $VHD_Path = $null
    $vmGUID = $VM.name

    #Start logical check that skips unused systems. They will not be powered off or on.
    If ($VMExcluded -eq $null)
    {
        $Query = "select * from Msvm_computersystem where Name='" + $vmGUID + "'"
        $VMTemp = gwmi -namespace root\virtualization -query $Query -ComputerName $HyperVParent

        #Only attempt a shutdown if the system is powered on
        If ($VMTemp.EnableState -ne "3")
        {
            Write-Host "System Requires Shutdown:", $VM.ElementName

            #Build SQL Query - Use the target GUID here since the Msvm_ShutdownComponent seems to be only targeted with a GUID
            $ShutdownQuery = "SELECT * from Msvm_ShutdownComponent WHERE SystemName ='" + $vmGUID + "'"
            #Execute the query to select the shutdown component of the target VM
            $vmshut = gwmi -namespace root\virtualization -query $ShutdownQuery -ComputerName $HyperVParent
            $result = $vmshut.InitiateShutdown("$true","VHD Backup Process");

            Write-Host "Shutting Down:", $VM.ElementName

            #Wait for system to shutdown
            Do {
                #Increment 1 sec pauses for each loop
                Start-Sleep -s 1
                #Use a different variable here so that the original target VM is not modified
                #Requery the VM each second to get an updated EnabledState
                $VMTemp = gwmi -namespace root\virtualization -query $Query -ComputerName $HyperVParent
                }
            While ($VMTemp.EnabledState -ne "3");
            Write-Host $VM.ElementName, "successfully shutdown"
        }
        Else
        {
            Write-Host $VM.ElementName, ": Already shutdown"
        }
    }
    #End Logical check for systems that are unused

    #Perform the file transfer of the VHD file afer the VM has shut down.
    Foreach ($VHD in $VirtualDiskResource)
        {
            $VHD_PATH = $VHD.Connection[0] + ","

            #Replace colon in path with dollar sign for UNC purposes
            $VHD_PATH_TEMP = $VHD.Connection[0] -replace ':','$'

            #Build Source String
            $BackupSource = "\\" + $HyperVParent + "\" + "VHD_PATH_TEMP"

            #Extract VHD Name from the path for use in the target file
            $VHDName = Split-Path -Leaf $VHD.Connection[0]

            #Build Target String; $TargetPath was built at the initiation of the script
            $BackupTarget = $TargetPath + "\" + $VHDName

            Write-Host "Beginning Backup:", $VM.ElementName, $BackupSource

            #Transfer VHD file to the target server using BITS
            StartBitsTransfer -Source $BackupSource -Destination $BackupTarget

            Write-Host "Backup Complete:", $VM.ElementName, $BackupTarget
        }

        #Here backed up systems are turned back on after the file transfer of their VHD is complete.
        #Filter out certain unused VMs - unused systems do not need to be booted.
        If ($VMExcluded -eq $null)
            {
                Write-Host "Starting VM:", $VM.ElementName
                #Boot the VM before the script loops and moves to the next system.
                $result = $VM.requeststatechange(2)
            }
    }
}

相关内容