2023-08-30

PowerShell Script to Change Public IP Address of VM on Azure

需搭配 Connect-AzAccount with Saved Encryped Credential in Powershell 實現自動化


Param (
    [String]$VMName = ''
);

if ($VMName -eq '') {
    exit;
};

Set-Location -Path ('C:\ChangeVMPublicIP');

if (Test-Path -Path (($VMName) + '.Lock')) {
    if ((Get-Date) -lt (Get-Item -Path (($VMName) + '.Lock')).LastWriteTime.AddMinutes(5)) {
        write-Host 'VM Locked';
        exit;
    };
};
$VMName | Out-File (($VMName) + '.Lock');

$CredentailFileName = 'AzCredential.txt';
$AzSubscriptionID = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';

##### Connect to Azure
[string[]]$CredentialRead = Get-Content -Path $CredentailFileName;
$UserName = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($CredentialRead[0]));
$Password = $CredentialRead[1] | ConvertTo-SecureString -Key (1..16)
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserName, $Password;
$ConnectAzAccount = Connect-AzAccount -Credential $Credential -Subscription $AzSubscriptionID;
##### Connect to Azure

$ScriptStartTime = (Get-Date).ToUniversalTime().AddHours(8).ToString('yyyy-MM-dd HH:mm:ss');

$DateTimeString = (Get-Date).ToUniversalTime().AddHours(8).ToString('yyyyMMdd HHmmss')
$TranscriptLog = (Get-Item -Path ".\" -Verbose).FullName + "\Logs\" + ("ChangeVMPublic " + $DateTimeString + ".log")
$StartLog = start-transcript -path $TranscriptLog;

$VM = Get-AzVM -Name $VMName;

if ($VM -eq $Null) {
    exit;
};

$NIC = Get-AzNetworkInterface -ResourceId $VM.NetworkProfile.NetworkInterfaces.Id;
$Subnet = Get-AzVirtualNetworkSubnetConfig -ResourceId $NIC.IpConfigurations.Subnet.Id;
$PublicIP = Get-AzPublicIpAddress | where {$_.Id -eq $NIC.IpConfigurations.PublicIpAddress.Id};

if ($PublicIP -eq $Null) {
    exit;
};

$OldPublicIPAddress = $PublicIP.IpAddress;
$NewPublicIPAddress = $PublicIP.IpAddress;

while ($NewPublicIPAddress -eq $OldPublicIPAddress) {
    $NIC.IpConfigurations.publicipaddress.id = $Null;
    $SetNIC = Set-AzNetworkInterface -NetworkInterface $NIC;

    $SetNIC = $NIC | Set-AzNetworkInterfaceIpConfig -Name $NIC.IpConfigurations.Name -PublicIPAddress $PublicIP -Subnet $Subnet;
    $SetNIC = $NIC | Set-AzNetworkInterface;

    $PublicIP = Get-AzPublicIpAddress | where {$_.Id -eq $NIC.IpConfigurations.PublicIpAddress.Id};
    $NewPublicIPAddress = $PublicIP.IpAddress;
    write-host ('Public IP Address of ' + $VMName + ' has been changed from ' + $OldPublicIPAddress + ' to ' + $NewPublicIPAddress);
};

Write-Host ('Script execution time: ' + [math]::Round((New-TimeSpan -Start $ScriptStartTime -End (Get-Date).ToUniversalTime().AddHours(8).ToString('yyyy-MM-dd HH:mm:ss')).TotalSeconds) + ' Seconds');

$EndLog = stop-transcript;

if (Test-Path -Path (($VMName) + '.Lock')) {
    Remove-Item -Path (($VMName) + '.Lock') -Confirm:$False;
    exit;
};

沒有留言:

張貼留言