Skip to content

Instantly share code, notes, and snippets.

@JerryBian
Last active October 29, 2019 09:49
Show Gist options
  • Save JerryBian/1ca8094bbab6a64f603d to your computer and use it in GitHub Desktop.
Save JerryBian/1ca8094bbab6a64f603d to your computer and use it in GitHub Desktop.
Azure Automation
workflow Auto-RestartVM
{
Param
(
[Parameter(Mandatory = $true)]
[String]
$AzureConnectionName,
[Parameter(Mandatory = $true)]
[String]
$AzureVMName,
[Parameter(Mandatory = $false)]
[String]
$AzureServiceName
)
Write-Output "job started!"
if($AzureServiceName -eq $null)
{
$AzureServiceName = $AzureVMName
}
$AzureConn = Get-AutomationConnection -Name $AzureConnectionName
if($AzureConn -eq $null)
{
throw "Could not retrieve '$AzureConnectionName' connection asset. Check that you created this first in the Automation service."
}
$Certificate = Get-AutomationCertificate -Name $AzureConn.AutomationCertificateName
if ($Certificate -eq $null)
{
throw "Could not retrieve '$AzureConn.AutomationCertificateName' certificate asset. Check that you created this first in the Automation service."
}
Set-AzureSubscription -SubscriptionName $AzureConnectionName -SubscriptionId $AzureConn.SubscriptionID -Certificate $Certificate
Select-AzureSubscription -SubscriptionName $AzureConnectionName
InlineScript
{
$VM = Get-AzureVM | where Name -eq $Using:AzureVMName
if($VM -eq $null)
{
throw "Could not find the '$Using:AzureVMName' virtual machine. Check that you created this first."
}
Write-Output "Restarting VM $Using:AzureVMName ..."
$VM | Restart-AzureVM
Write-Output "Restarted VM $Using:AzureVMName"
$WinRMCert = ($VM | select -ExpandProperty vm).DefaultWinRMCertificateThumbprint
$AzureX509Cert = Get-AzureCertificate -ServiceName $Using:AzureServiceName -Thumbprint $WinRMCert -ThumbprintAlgorithm sha1
if((Test-Path Cert:\LocalMachine\Root\$WinRMCert) -eq $false)
{
$certByteArray = [System.Convert]::fromBase64String($AzureX509cert.Data)
$CertToImport = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList (,$certByteArray)
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store "Root", "LocalMachine"
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($CertToImport)
$store.Close()
}
$Uri = Get-AzureWinRMUri -ServiceName $Using:AzureServiceName -Name $Using:AzureVMName
$secpasswd = ConvertTo-SecureString "password" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
$PSCommandResult = Invoke-command -ConnectionUri $Using:Uri.AbsoluteUri -credential $Using:mycreds -ScriptBlock { Invoke-Expression "D:\start.ps1" }
$PSCommandResult
}
Write-Output "job completed!"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment