Skip to content

Instantly share code, notes, and snippets.

@JPRuskin
Created March 5, 2020 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JPRuskin/932a5c57ff20e593c2e9c615332c4cf4 to your computer and use it in GitHub Desktop.
Save JPRuskin/932a5c57ff20e593c2e9c615332c4cf4 to your computer and use it in GitHub Desktop.
using namespace Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters
function Invoke-AzVMScript {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ResourceGroupCompleter()]
[string]$ResourceGroupName,
[Parameter(Mandatory)]
[ResourceNameCompleter("Microsoft.Compute/virtualMachines", "ResourceGroupName")]
[string]$VMName,
[Parameter(Mandatory, ParameterSetName = 'ScriptBlock')]
[ScriptBlock]$ScriptBlock,
[Parameter(Mandatory, ParameterSetName = 'File')]
[string]$ScriptPath,
[HashTable]$Parameter
)
if ($ScriptBlock) {
$ScriptPath = (New-Item -Path $env:Temp -Name "$(New-Guid).ps1" -Value $ScriptBlock.ToString()).FullName
}
$Parameters = @{
ResourceGroupName = $ResourceGroupName
VMName = $VMName
CommandId = "RunPowerShellScript"
ScriptPath = $ScriptPath
}
if ($Parameter) {
$Parameters.Parameter = $Parameter
}
$Result = Invoke-AzVmRunCommand @Parameters
if ($Result.Status -eq 'Succeeded') {
switch ($Result.Value) {
{$_.Code -eq 'ComponentStatus/StdOut/succeeded'} {
$_.Message
if ($_.Message.Length -eq 4096) {
Write-Warning "Message is exactly 4096 characters long, and was likely truncated"
}
}
{$_.Code -eq 'ComponentStatus/StdErr/succeeded' -and $_.Message} {
Write-Error $_.Message
}
}
} else {
$Result
}
if ($ScriptBlock) {
Remove-Item $ScriptPath
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment