Unable to script using Multi-threading

Copper Contributor
  • I have one Csv and there are 10 VM and i want to run this script to all the vms in same time (using  Multi-threading  concept or any other method) not one by one.
  • because if it will run one by one then take a lots of time.

 

 

$VMNAME=Import-Csv -Path "C:\Test_powershell_03-07-20\09-08-20\demovm.csv" 
foreach($vm in $VMNAME)
{
$flag="false"
$Subscriptionid =$_.Subscriptionid
$Name =$_.VMNAME
$ResourceGroupName = $_.RGN
$Location=$_.Location
Select-AzureRmSubscription -SubscriptionId 
$Subscriptionid
$VMNAME = Get-azurermvm -status -Name $Name -ResourceGroupName $ResourceGroupName $Status   = $VMNAME.Statuses[1].DisplayStatus
if($Status -eq "vm deallocated")
{ 
start-azurermvm -Name $_.VMNAME -ResourceGroupName $_.RGN 
$flag="true"  
}
if($flag -eq "true")
{
stop-azurermvm -Name $_.VMNAME -ResourceGroupName $_.RGN -Force 
}  
catch {   
Write-Output $Error[0].Exception.Message
}
}

 

 

 

 

 

4 Replies

@Pradeep MISHRA - You can use -AsJob option which will create each execution as a job for you and will run in the background

You can then track the status of the Job based on the object returned.

Hello @Pradeep MISHRA

If you are able to use PowerShell 7 you may want to consider the new parallel option for the foreach-object Cmdlet.

https://docs.microsoft.com/en-us/powershell/scripting/whats-new/what-s-new-in-powershell-70?view=pow... 

I hope that helps

Cheers
Rolf
#MCT #LearnWithRolf #TheCloud42 

@Rolf-42 ,

 

I am using below powershell version and unable to using workflow

 

PS C:\Users\Admin> Get-Host | Select-Object Version

Version
-------
5.1.19041.1

 

Can you please share a sample ?

Hello @Pradeep MISHRA

Since your PowerShell version is to low what about running PowerShell 7 in a container? https://www.thomasmaurer.ch/2020/03/run-azure-powershell-in-a-docker-container/ 

If that is not possible the background job feature is your approach https://docs.microsoft.com/en-us/powershell/scripting/developer/cmdlet/background-jobs?view=powershe...

Start-Job -ScriptBlock { Get-Process -Name powershell } is the example you are looking for.

The example is taken from the Start-Job documentation here: https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Core/Start-Job?view=powershe...

Cheers
Rolf
#MCT #LearnWithRolf #TheCloud42