Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example for using Set-AzureRmVMCustomScriptExtension with a script stored in an Azure Blob Container
param
(
[parameter(Mandatory=$true)]
[string]$VMResourceGroupName,
[parameter(Mandatory=$true)]
[string]$VMLocation,
[parameter(Mandatory=$true)]
[string]$VMName,
[parameter(Mandatory=$true)]
[string]$ScriptName,
[parameter(Mandatory=$false)]
[string]$ScriptArguments,
[parameter(Mandatory=$true)]
[string]$StorageResourceGroupName,
[parameter(Mandatory=$true)]
[string]$StorageAccountName,
[parameter(Mandatory=$true)]
[string]$StorageContainerName
)
Set-AzureRmCurrentStorageAccount -ResourceGroupName $StorageResourceGroupName -Name $StorageAccountName
if (!(Get-AzureRmStorageContainer -ResourceGroupName $StorageResourceGroupName -AccountName $StorageAccountName -ContainerName $StorageContainerName -ErrorAction SilentlyContinue))
{
Write-Verbose "Existing container not found: $StorageContainerName. Cannot continue."
throw("Existing container $StorageContainerName for script file could not be found, exiting.")
}
try
{
Write-Verbose "Checking for script in blob container..."
Get-AzureStorageBlob -Blob $ScriptName -Container $StorageContainerName | Write-Verbose
}
catch
{
Write-Verbose "Blob not found!"
throw("No script file found in blob storage. Please verify script is available in the container specified.")
}
$cseName = "CustomScriptExtension"
$vm = Get-AzureRmVM -ResourceGroupName $VMResourceGroupName -Name $VMName
$cseExtension = $vm.Extensions | where { $_.Publisher -eq "Microsoft.Compute" -and $_.VirtualMachineExtensionType -eq "CustomScriptExtension" }
# If there is an existing CustomScriptExtension, we need to use the same name for the extension
if ($cseExtension)
{
$cseName = $cseExtension.Name
}
if ($ScriptArguments)
{
Write-Verbose "Running script with arguments: $ScriptArguments"
Set-AzureRmVMCustomScriptExtension -Name $cseName -Location $VMLocation -ResourceGroupName $VMResourceGroupName -VMName $VMName -StorageAccountName $StorageAccountName -ContainerName $StorageContainerName -FileName $ScriptName -Run $ScriptName -Argument $ScriptArguments
}
else
{
Write-Verbose "Running script with no arguments."
Set-AzureRmVMCustomScriptExtension -Name $cseName -Location $VMLocation -ResourceGroupName $VMResourceGroupName -VMName $VMName -StorageAccountName $StorageAccountName -ContainerName $StorageContainerName -FileName $ScriptName -Run $ScriptName
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.