SOLVED

How to run Powershell command in Loop

Contributor

Hi,

 

I am new to Powershell script and Need your help on below requirement.

 

I am have powershell script displaying last last 3 commands and output of my powershell script.

 

Below last 3 command lines:

 

$FinalResource=$FinalResource1 | Where-Object{$_.ResourceType -ne $MetricType}

Write-Output $FinalResource

New-AzResourceLock -LockLevel CanNotDelete -LockName Delete_Lock -ResourceName $FinalResource.Name -ResourceType $FinalResource.ResourceType -ResourceGroupName xxxxxx

 

Below is Output of my powershell script:

 

resourcelock.PNG

 

I am getting list of resources which are not having LOCKS on Azure after that I am applying lock on each resource by using above command.

 

Script is running fine when I am passing single resource but script is failing when I am passing all resources.

 

How to run last command in loop by passing one by one resource so that lock command will apply on all resources.

 

Thanks,

Brahma

5 Replies
best response confirmed by Brahmaiah (Contributor)
Solution

@Brahmaiah You can use Foreach and set the lock for each member. Let me know if you have any questions. 

$FinalResource = $FinalResource1 | Where-Object{$_.ResourceType -ne $MetricType}

Write-Output $FinalResource
$Counter = $FinalResource.count

Foreach($Item in $FinalResource)
 {
  Write-Host "($Counter) Locking Resource: $($Item.Name)"
  New-AzResourceLock -LockLevel CanNotDelete -LockName Delete_Lock -ResourceName $Item.Name -ResourceType $Item.ResourceType -ResourceGroupName $Item.ResourceGroupName
  $Counter--
 }


 

@Erick A. Moreno R.  Thank you so much Sir. It is working perfectly.

 

Can you also help me how to avoid confirm option while running the script, I have to click Yes for each resource to execute command.

 

Below is screen shot.

resourcelock.PNG

 

Thanks

@BrahmaiahErick A. Moreno R.@Brahmaiah

-Force worked by keeping end of statement. thanks for all your help, your help saved me lot of time and work.

@Brahmaiah Glad to help, for the auto-confirm you can use the switch -confirm:$false at the end of the lock command, let me know if you need further assistance. 

Regards

Erick Moreno

How To Manage Windows Processes With PowerShell?
Learn More: https://velaninfo.com/rs/techtips/windows-process-with-powershell/