Search code examples
pythonpowershellazure-cliazure-cli2

Azure Python CLI: launch script with run-command invoke fails when passing the script file with @ but not with inline commands


I have a project designed to launch PowerShell scripts to run in Azure VMs using AZCLI with the following structure

* /myAPP
  * /main (package)
    * main.py
    * /util (package)
        * auth.py
        * launchscript.py
        * testscript.ps1

main.py calls class from launchscript.py in order to launch the script itself.

  1. If I launch the PS script to a VM using the inline option it works
import azure.cli.core as azclicor
output = azclicor.get_default_cli().invoke(['vm','run-command','invoke','--command-id','RunPowerShellScript','--name','VM1','-g','VM_RG','--scripts','hostname'])
  1. When I launch it with the script that's inside the module it fails
import azure.cli.core as azclicor
output = azclicor.get_default_cli().invoke(['vm','run-command','invoke','--command-id','RunPowerShellScript','--name','VM1','-g','VM_RG','--scripts','`@testscript.ps1'])

ERROR: "The term 'testscript.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program." just as if I used another name of a script that does not exists. So it seems its failing to find the script, even though its on the same folder than the module calling it.

However, in another test project I have:

* /myAPPTest
  * /util (package)
    * main.py
    * auth.py
    * launchscript.py
    * testscript.ps1

The method using @ works, with exactly the same code. I think the issue might be with the modules and how Python loads them, but I am really confused and don't know what to test in order to make the first (more nested) version work


Solution

  • Regarding the issue, please refer to the following code

    My project structure

      * /cli (package)
        * main.py
        * /util (package)
            * test.ps1
    

    My powershell file

    Get-Process | Out-File -FilePath C:\Process.txt
    

    my code

    import azure.cli.core as azclicor
    import os.path as path
    
    t=path.dirname(path.abspath(__file__))+'/until/test.ps1'
    file_path=t.replace('\\','/')
    
    output = azclicor.get_default_cli().invoke(['vm','run-command','invoke','--command-id',
            'RunPowerShellScript','--name','worker','-g','worker_group',
            '--scripts', f'@{file_path}'])
    

    Result

    enter image description here enter image description here