#$cred = Get-Credential # または #(事前に Get-Credential | Export-Clixml $HOME\vm01-cred.xml でXMLを作成) #$cred = Import-Clixml $HOME\vm01-cred.xml # または $username = ".\Administrator" $password = "P@ssw0rd!" $securePassword = ConvertTo-SecureString $password -AsPlainText -Force $cred = [PSCredential]::new($username, $securePassword) $vmName = "vm01" $testScriptPath = "E:\Tools\TestScript.ps1" $guestTargetPath = "C:\" $vm = Get-VM -Name $vmName -ErrorAction Stop # Create Checkpoint $vm | Checkpoint-VM -SnapshotName "PreTest" $lastcheckpoint = $vm | Get-VMSnapshot | Sort CreationTime | Select -Last 1 # Enable VMGuestSvc $guestSvcDefault = (Get-VMIntegrationService -VMName $vm.Name "ゲスト サービス インターフェイス").Enabled if (!$guestSvcDefault) { Enable-VMIntegrationService -VMName $vm.Name "ゲスト サービス インターフェイス" } # Start VM $vm | start-VM -ErrorAction Stop while ($vm.Heartbeat -notlike "Ok*") { Start-Sleep -Seconds 1 } Write-Host "$($vm.Name) is Up." # Copy Test Script Copy-VMFile ーName $vm.Name -SourcePath $testScriptPath -DestinationPath $guestTargetPath -FileSource Host -Force # Run Test $testScript = Join-Path "C:\" (Split-Path $testScriptPath -Leaf) $result = Invoke-Command -VMName $vm.Name -Credential $cred -ScriptBlock { & $using:TestScript } # Restore and Remove Checkpoint $lastcheckpoint | Restore-VMSnapshot -Confirm:$false $lastcheckpoint | Remove-VMSnapshot # Test result $result