Azure Invoke-Azvmruncommand -

I am wondering if there is way to use the Invoke-AzVMRunCommand to run a single command, rather than a powershell ps1 file?

As an example, I want to execute a single command... "C:\app\app.exe -c exit". Without the need to push a powershell commandlet to the system.

I am able to do this via the Azure Portal "RunPowerShellScript" and it works but would like to do it to multiple systems via the command line via Invoke-AzVMRunCommand. These systems do not share a command account that can be used.

According to Microsoft, here is the syntax... Invoke-AzVMRunCommand -ResourceGroupName 'rgname' -VMName 'vmname' -CommandId 'RunPowerShellScript' -ScriptPath 'sample.ps1' -Parameter @{param1 = "var1"; param2 = "var2"}

I don't want to run a script, I merely want to be able to execute a command on the system. Is this possible?

3

2 Answers

There is no direct way of doing it. But, you can write a script block and generate a file from it and then run Invoke-AzVMRunCommand using that file and later on delete that file if required.

$Server = "server01"
[System.String]$ScriptBlock = {Get-Process}
$FileName = "RunScript.ps1"
Out-File -FilePath $FileName -InputObject $ScriptBlock -NoNewline
$vm = Get-AzVM -Name $Server
Invoke-AzVMRunCommand -ResourceGroupName $vm.ResourceGroupName -Name $Server -CommandId 'RunPowerShellScript' -ScriptPath $FileName
Remove-Item -Path $FileName -Force -ErrorAction SilentlyContinue
2

It's now possible to use the:

-ScriptString

... option, however you need to ensure that the Az version will support it.

Azure Pipelines as of 2022-07-21 don't support it: "A parameter cannot be found that matches parameter name 'ScriptString'."

See the documentation:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest