49 lines
1.4 KiB
PowerShell
49 lines
1.4 KiB
PowerShell
param(
|
|
[string]$VMName,
|
|
[string]$IP,
|
|
[int]$MaskBits,
|
|
[string]$Gateway,
|
|
[string]$DNS,
|
|
[string]$GuestUser,
|
|
[string]$GuestPassword
|
|
)
|
|
|
|
$sec = ConvertTo-SecureString $GuestPassword -AsPlainText -Force
|
|
$cred = New-Object pscredential($GuestUser, $sec)
|
|
|
|
try {
|
|
$vm = Get-VM -Name $VMName -ErrorAction Stop
|
|
|
|
if ($vm.PowerState -ne 'PoweredOn') {
|
|
[pscustomobject]@{ status="error"; message="VM is powered off" } | ConvertTo-Json
|
|
exit
|
|
}
|
|
|
|
if ($vm.ExtensionData.Guest.ToolsStatus -notin @('toolsOk','toolsOld')) {
|
|
[pscustomobject]@{ status="error"; message="VMware Tools not ready" } | ConvertTo-Json
|
|
exit
|
|
}
|
|
|
|
$script = @"
|
|
`$adapter = Get-NetAdapter | Where-Object { `$_.Status -eq 'Up' } | Select-Object -First 1
|
|
Remove-NetIPAddress -InterfaceIndex `$adapter.ifIndex -Confirm:`$false -ErrorAction SilentlyContinue
|
|
Remove-NetRoute -InterfaceIndex `$adapter.ifIndex -Confirm:`$false -ErrorAction SilentlyContinue
|
|
New-NetIPAddress -InterfaceIndex `$adapter.ifIndex -IPAddress "$IP" -PrefixLength $MaskBits -DefaultGateway "$Gateway"
|
|
Set-DnsClientServerAddress -InterfaceIndex `$adapter.ifIndex -ServerAddresses "$DNS"
|
|
"@
|
|
|
|
$res = Invoke-VMScript -VM $vm -ScriptText $script -GuestCredential $cred -ScriptType PowerShell
|
|
|
|
[pscustomobject]@{
|
|
status="ok"
|
|
message="IP updated"
|
|
ip=$IP
|
|
} | ConvertTo-Json
|
|
|
|
} catch {
|
|
[pscustomobject]@{
|
|
status="error"
|
|
message=$_.Exception.Message
|
|
} | ConvertTo-Json
|
|
}
|