Files
portal-api/resources/scripts/vm/verifyIPWindows.ps1

59 lines
2.0 KiB
PowerShell

# verifyIPWindows.ps1
# Deploy to: C:\CLISave\AssignIP\verifyIPWindows.ps1 on the vSphere Windows host
#
# Usage: powershell -ExecutionPolicy Bypass -NonInteractive -File verifyIPWindows.ps1 \
# <vm_id> <ip> <vcenter_host> <vcenter_user> <vcenter_password> <guest_password>
#
# Checks that the IP is configured and not in Duplicate state inside the Windows guest.
# Output: SUCCESS | FAIL (exactly one line)
param(
[Parameter(Mandatory=$true)][string]$VmId,
[Parameter(Mandatory=$true)][string]$Ip,
[Parameter(Mandatory=$true)][string]$VCenterHost,
[Parameter(Mandatory=$true)][string]$VCenterUser,
[Parameter(Mandatory=$true)][string]$VCenterPassword,
[Parameter(Mandatory=$true)][string]$GuestPassword
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
try {
Import-Module VMware.VimAutomation.Core -ErrorAction Stop
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false | Out-Null
Set-PowerCLIConfiguration -Scope User -ParticipateInCEIP $false -Confirm:$false | Out-Null
Connect-VIServer -Server $VCenterHost -User $VCenterUser -Password $VCenterPassword -Force -ErrorAction Stop | Out-Null
$vm = Get-VM -Id "VirtualMachine-$VmId" -ErrorAction Stop
# PowerShell snippet run inside the Windows guest
$guestScript = @"
`$ErrorActionPreference = 'SilentlyContinue'
`$addr = Get-NetIPAddress -IPAddress '$Ip' -ErrorAction SilentlyContinue
if (`$addr -and `$addr.AddressState -ne 'Duplicate' -and `$addr.AddressState -ne 'Invalid') {
Write-Output 'SUCCESS'
} else {
Write-Output 'FAIL'
}
"@
$result = Invoke-VMScript -VM $vm `
-ScriptText $guestScript `
-GuestUser "administrator" `
-GuestPassword $GuestPassword `
-ScriptType Powershell `
-ErrorAction Stop
if ($result.ScriptOutput -match "SUCCESS") {
Write-Output "SUCCESS"
} else {
Write-Output "FAIL"
}
} catch {
Write-Output "FAIL"
} finally {
Disconnect-VIServer -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
}