how to invoke a batch file inside a virtual machine using powershell?

Azure-search 201 Reputation points
2024-03-07T08:08:50.2966667+00:00

Hi,

I have a batch file residing in my azure virtual machine which i need to run using powershell.

I am already using Invoke-AzVMRunCommand, but it still prompts the error.

Below is the powershell script that i am using:

Invoke-AzVMRunCommand -ResourceGroupName $resourceGroupName -VMName $vmName -CommandId 'RunPowerShellScript' -ScriptPath C:\firstpath\secondpath\reset.bat

I am getting the below error:

Invoke-AzVMRunCommand: Cannot find drive. A drive with the name 'C' does not exist.

I followed the documentation https://learn.microsoft.com/en-us/azure/virtual-machines/windows/run-command

Any kind of help is appreciated!

Azure Virtual Machines
Azure Virtual Machines
An Azure service that is used to provision Windows and Linux virtual machines.
7,586 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,329 questions
0 comments No comments
{count} votes

Accepted answer
  1. TP 83,971 Reputation points
    2024-03-07T16:21:49.02+00:00

    Hi,

    ScriptPath is referring to the local path where you are executing Invoke-AzVMRunCommand from, NOT the path within the VM. It is expecting to be able find the file locally and send it to the VM for execution.

    Instead you can use -ScriptString using sample code below:

    Invoke-AzVMRunCommand -ResourceGroupName $resourceGroupName -VMName $vmName -CommandId 'RunPowerShellScript' -ScriptString C:\firstpath\secondpath\reset.bat
    
    

    Please click Accept Answer and upvote if the above was helpful.

    Thanks.

    -TP


1 additional answer

Sort by: Most helpful
  1. vipullag-MSFT 26,021 Reputation points
    2024-03-07T08:58:03.9933333+00:00

    Hello Azure-search

    Welcome to Microsoft Q&A Platform, thanks for posting your query here.

    It looks like the error is occurring because the RunPowerShellScript command is expecting a PowerShell script, but you are passing it a batch file.

    To run a batch file using Invoke-AzVMRunCommand, you can try and use the RunCommandScript command instead.

    This command will run the batch file located at C:\firstpath\secondpath\reset.bat on the virtual machine named $vmName in the resource group named $resourceGroupName.

    Please make sure that the path to the batch file is correct and that the file exists on the virtual machine.

    Hope this helps.