48 lines
2.2 KiB
PowerShell
48 lines
2.2 KiB
PowerShell
# assignIPWindows.ps1
|
|
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
|
|
)
|
|
|
|
$guestScript = @"
|
|
`$ErrorActionPreference = 'Stop'
|
|
try {
|
|
`$adapter = Get-NetAdapter | Where-Object { `$_.Status -eq 'Up' -and `$_.InterfaceDescription -notlike '*Loopback*' } | Sort-Object InterfaceIndex | Select-Object -First 1
|
|
if (-not `$adapter) { throw 'No active network adapter found' }
|
|
Get-NetIPAddress -InterfaceIndex `$adapter.InterfaceIndex -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
|
|
New-NetIPAddress -InterfaceIndex `$adapter.InterfaceIndex -IPAddress '$Ip' -PrefixLength $Cidr -DefaultGateway '$Gateway' -ErrorAction Stop | Out-Null
|
|
Write-Output 'SUCCESS'
|
|
}
|
|
catch {
|
|
Write-Output "FAIL: `$(`$PSItem.Exception.Message)"
|
|
}
|
|
"@
|
|
|
|
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
|
|
$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
|
|
}
|