简体   繁体   中英

How to run a long running .CMD file inside an Azure VM as a background job using powershell

I have copied a folder from a container to all azure vms in my subscription using custom script extension. I have a.cmd file inside that folder which i need to run on each and every vm in my subscription. The.cmd file is a long running command which never ends. I need to run it in background. I have tried invoke-command, start-process, invoke-expression, invoke-azvmruncommand -asjob etc. but nothing is actually triggering the.cmd file. I can run it by logging into vm or directly running it from runcommand, but i want to run it in background. I have also tried setting up scheduled task, but of no use. Is there any way to do this in a more effective way.?

You cannot pass a variable in a ScriptBlock directly. Use the '-ArgumentList' parameter or a 'Using' variable. This applies to Start-Job, Invoke-Command, etc.

This ScriptBlock won't execute properly because the value of $path will always be null:

Start-Job -ScriptBlock { set-location $path ; &filename.cmd }

While these command will work:

# With '-ArgumentList' parameter
Start-Job -ScriptBlock { Set-Location $args[0] ; &.\filename.cmd } -ArgumentList $path

# With 'Using' variable
Start-Job -ScriptBlock { Set-Location $Using:path ; &.\filename.cmd }

Note that the latest version of Powershell added an Argument to be able to specify the Working Directory for the Start-Job and Invoke-Command cmdlets ( -WorkingDirectory )

While testing, I noticed some issues most probably related to the Set-Location command when used in jobs. Without going in much details, I found it more reliable to run it this ways:

# With '-ArgumentList' parameter
Start-Job -ScriptBlock { &"$($args[0])filename.cmd" } -ArgumentList $path

# With 'Using' variable
Start-Job -ScriptBlock { &"$($Using:path)filename.cmd" }

Finally, you may consider using the Start-Process cmdlet instead of Start-Job if it applies to your case. Start-Process allows you to continue your script's execution without waiting for the *.cmd batch to finish... and it's simplier to use:

Start-Process -FilePath "filename.cmd" -WorkingDirectory $path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM