Private/Submit-ScriptToVmAndExecute.ps1
function Global:Submit-ScriptToVmAndExecute { [CmdletBinding()] <# .SYNOPSIS Initializes the newly created VM .DESCRIPTION ... #> param( [Parameter(Mandatory = $true)] [string] $ResourceGroupName, [Parameter(Mandatory = $true)] [string] $ResourceLocation, [Parameter(Mandatory = $true)] [string] $VMName, [Parameter(Mandatory = $true)] [ValidateSet('InstallD365Module','InitVM','DownloadBC','InstallBC','GeneralizeVM','WriteProperties','CreateUpdateScheduledTask')] [string] $ScriptBlockName, [Parameter(Mandatory = $false)] $RunParameter, [Parameter(Mandatory = $true)] [string] $MsgBeforeExecuting ) process { . $PSScriptRoot\Scriptblocks.ps1 $tagName = "Command $ScriptBlockName" $vm = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName if ($vm.Tags.ContainsKey($tagName)){ Write-CustomHost -Message "Command $ScriptBlockName was already executed." return } if ($MsgBeforeExecuting){ Write-CustomHost -Message $MsgBeforeExecuting } $fullscriptpath = New-TemporaryFile | Rename-Item -NewName { $_ -replace 'tmp$', 'ps1' } -PassThru | Select-Object -ExpandProperty FullName $content = "" switch ($ScriptBlockName) { 'InstallD365Module' { $content = $installD365Module } 'InitVM' { $content = $initializeVm } 'DownloadBC' { $content = $downloadBCDVD } 'InstallBC' { $content = $installBC } 'GeneralizeVM' { $content = $generalizeVM } 'WriteProperties' { $content = $writeProperties } 'CreateUpdateScheduledTask' { $content = $createUpdateScheduledTask } } Set-Content -Path $fullscriptpath -Value $content Write-CustomHost -Message "Running command '$ScriptBlockName' on VM $VMName..." # Tag VM $resource = Get-AzResource -ResourceGroupName $ResourceGroupName -Name $VMName $existingTags = $vm.Tags if ($existingTags.Count -ne 0){ $existingTags.Add($tagName, "Executed") Set-AzResource -ResourceId $resource.Id -Tag $existingTags -Force | Out-Null } else { Set-AzResource -ResourceId $resource.Id -Tag @{$tagName = "Executed"} -Force | Out-Null } Invoke-AzVMRunCommand -ResourceGroupName $ResourceGroupName -VMName $VMName -CommandId 'RunPowerShellScript' -ScriptPath $fullscriptpath -Parameter $RunParameter | Out-Null Write-CustomHost -Message "Command completed." Remove-Item $fullscriptpath -Force } } |