# assignIPWindows.ps1 # Deploy to: C:\CLISave\AssignIP\assignIPWindows.ps1 on the vSphere Windows host # # Usage: powershell -ExecutionPolicy Bypass -NonInteractive -File assignIPWindows.ps1 \ # # # Output: SUCCESS | FAIL (exactly one line) param( [Parameter(Mandatory = $true)][string]$VmId, [Parameter(Mandatory = $true)][string]$Ip, [Parameter(Mandatory = $true)][string]$Gateway, [Parameter(Mandatory = $true)][string]$Cidr, [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 script executed inside the Windows guest via VMware Tools $guestScript = @" $ErrorActionPreference = 'Stop' try { # Find the first active ethernet adapter that is not a loopback $adapter = Get-NetAdapter | Where-Object { $_.Status -eq 'Up' -and $_.InterfaceDescription -notlike '*Loopback*' } | Sort-Object -Property InterfaceIndex | Select-Object -First 1 if (-not $adapter) { throw 'No active network adapter found' } # Remove existing IPv4 addresses and routes on this interface $adapter | Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Remove-NetIPAddress -Confirm:$false -ErrorAction SilentlyContinue Get-NetRoute -InterfaceIndex $adapter.InterfaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue | Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue # Set new static IP New-NetIPAddress -InterfaceIndex $adapter.InterfaceIndex -IPAddress '$Ip' -PrefixLength $Cidr -DefaultGateway '$Gateway' -ErrorAction Stop | Out-Null Write-Output 'SUCCESS' } catch { 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" Write-Output $_.Exception.Message } finally { Disconnect-VIServer -Confirm:$false -ErrorAction SilentlyContinue | Out-Null }