Issues having a retry count work in powershell - azure

I have a Powershell script that checks on a set of VM status before starting them. If the VM'S are in deallocating mode there should be a sleep and retry on 30 seconds. The code does not do a a retry. The code does a vm start in batches on 2 for vm's with wilcards as mentioned below in an order.
Need help if possible
$ResName= "resvmtest"
$action="start"
if($action -eq "start"){
$vnames=#('*dom*','*DBs*','*')
foreach($vname in $vnames) {
Write-Host "Starting VM with "$vname
$vmList = Get-AzVM -ResourceGroupName $ResName -Name $vname -Status | Select-Object Name, PowerState, ResourceGroupName
do{
$batch = #{
Skip = 0
First = 2
}
do{
foreach($vm in ($vmList | Select-Object #batch)){
$Stoploop = $false
[int]$Retrycount = "0"
do {
try {
if($vm.PowerState -eq "VM Deallocated"){
Write-Host "Job completed"
$Stoploop = $true
}
}
catch {
if ($vm.PowerState -eq "VM Deallocatting") {
Write-Host "VM Still not Deallocated"
Start-Sleep -Seconds 10
$Retrycount = $Retrycount + 1
}
}
}
While ($Stoploop -eq $false)
$params = #($vm.Name, $vm.ResourceGroupName,$vm.PowerState)
$job = Start-Job -ScriptBlock {
param($ComputerName,$serviceName,$statuses)
Start-AzVM -Name $ComputerName -ResourceGroupName $serviceName
} -ArgumentList $params
}
Wait-Job -Job $job
Get-Job | Receive-Job
$batch.Skip += 2
}
until($batch.skip -ge $vmList.count)
}
while($job.state -ne "Completed")
}
}

If you just want to wait for a VM's PowerState turns to VM Deallocated from VM Deallocatting, try the code below:
$vms = Get-AzVm -Status| Select-Object Name, PowerState,ResourceGroupName
#pick certain vm for demo here.
$vm = $vms[1]
$retryCount = 0
while($vm.PowerState -eq 'VM deallocating'){
Write-Host "waiting for VM deallocated..."
Start-Sleep -Seconds 5
$retryCount +=1
Write-Host "check count:$retryCount"
#get latest vm status
$vm.PowerState = (Get-AzVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Status).Statuses[1].DisplayStatus
Write-Host "vm current state:"$vm.PowerState
}
Write-Host "vm new state:" + $vm.PowerState
Result:

Related

My Powershell script is not explicitly calling for any specific resources but I am getting "ErrorCode: TargetResourceNotFound" error

My Powershell script is not explicitly calling for any specific resources but I am getting "ErrorCode: TargetResourceNotFound" error. I have attached the error in the image. What am I missing?
$subs = Get-AzSubscription | Where-Object {$_.Name -like "*-NonProd"}
foreach ($sub in $subs)
{
Select-AzSubscription -SubscriptionId $sub.Id
$RGs = Get-AzResourceGroup | Where-Object {$_.ResourceGroupName -like "*Infra"}
foreach ($RG in $RGs)
{
$NetworkWatchers = Get-AzNetworkWatcher
$NSGs = (Get-AzNetworkSecurityGroup).Id
foreach ($NSG in $NSGs)
{
foreach ($NetworkWatcher in $NetworkWatchers)
{
$Status = Get-AzNetworkWatcherFlowLogStatus -NetworkWatcherName $NetworkWatcher.Name
ResourceGroupName $RG.ResourceGroupName -TargetResourceId $NSG -Verbose
}
if (($Status).Enabled -eq $true)
{
Write-Output "$NSG in $(($sub).Name) has FlowLogs Enabled" | Tee-Object -FilePath 'C:\Users\user1\downloads\Output.txt' -Verbose -Append
}
if (($Status).Enabled -ne $true)
{
Write-Output "$NSG in $(($sub).Name) does not have FlowLogs Enabled" | Tee-Object -FilePath 'C:\Users\user1\downloads\Output.txt' -Verbose -Append
}
}
}
}
enter code here
Error Attached
Network Watchers are usually in a hidden resource group, and perhaps you are trying to find one in one of the available RGs. Try omitting the RG factor and use
$subs = Get-AzSubscription | Where-Object { $_.Name -like "*-NonProd" }
foreach ($sub in $subs) {
Select-AzSubscription -SubscriptionId $sub.Id
$NetworkWatchers = Get-AzNetworkWatcher
$NSGs = (Get-AzNetworkSecurityGroup).Id
foreach ($NSG in $NSGs) {
foreach ($NetworkWatcher in $NetworkWatchers) {
$Status = Get-AzNetworkWatcherFlowLogStatus -NetworkWatcher $NetworkWatcher -TargetResourceId $NSG -Verbose
}
if (($Status).Enabled -eq $true) {
Write-Output "$NSG in $(($sub).Name) has FlowLogs Enabled" | Tee-Object -FilePath 'C:\Users\user1\downloads\Output.txt' -Verbose -Append
}
if (($Status).Enabled -ne $true) {
Write-Output "$NSG in $(($sub).Name) does not have FlowLogs Enabled" | Tee-Object -FilePath 'C:\Users\user1\downloads\Output.txt' -Verbose -Append
}
}
}
I am able to get all flow logs configuration status.
Here is another approach:
I tried to reproduce the same in my environment and got the same error as below:
The error TargetResourceNotFound usually occurs if you are passing invalid resource group name or subscription name.
To confirm whether the resource group or subscription exists, execute the below code lines separately like below:
$subs = Get-AzSubscription | Where-Object {$_.Name -like "*-name"}
$subs
$RGs = Get-AzResourceGroup | Where-Object {$_.ResourceGroupName -like "*name"}
$RGs
The error states that Target resource identifier /subscriptions/subid/resourceGroups/RG/providers/Microsoft.Network/networkWatchers/*** not found in the region westeurope. Cross-verify whether the Network Watcher exists.
I am able to get the status of the Network Watcher successfully when I passed valid subscription and Resource group like below:
If the error still persists, try excluding the $RGs = Get-AzResourceGroup | Where-Object {$_.ResourceGroupName -like "*name"} and execute.
I appreciate your assistance.
I got it working by changing -NetworkWatcherName $NetworkWatcher.Name to -NetworkWatcherName $NetworkWatcher.ResourceGroupName
foreach ($NSG in $NSGs)
{
# $NSG.Id
# $NSGid = $NSG.Id
foreach ($NetworkWatcher in $NetworkWatchers)
{
$Status = Get-AzNetworkWatcherFlowLogStatus -NetworkWatcherName $NetworkWatcher.ResourceGroupName -ResourceGroupName $RG.ResourceGroupName -TargetResourceId $NSG -Verbose -ErrorAction SilentlyContinue
if (($Status).Enabled -eq $true)
{
Write-Output "$NSG in $(($sub).Name) has FlowLogs Enabled" | Tee-Object -FilePath 'C:\Users\A240379\downloads\OutEnabled.csv' -Verbose -Append
}
if (($Status).Enabled -ne $true)
{
Write-Output "$NSG in $(($sub).Name) does not have FlowLogs Enabled" | Tee-Object -FilePath 'C:\Users\A240379\downloads\OutNotEnabled.csv' -Verbose -Append
}
}
}

Starting azure VM in parallel and validate after in PowerShell

Context : I am automating starting of 3 Azure VM through a PowerShell script, and each VM is taking 4-5min to start. I want to run the start command parallel and after 5-6min verify them whether they are started.
function restartLoadAgents ($AzuresecretValue,$AzureApplicationID,$AzureObjectID,$AzureDirectoryID,$AzureUserName,$AzureSubscriptionID) {
$password = ConvertTo-SecureString $AzuresecretValue -AsPlainText -Force;
$LoadAgentResourceGroup = "test-performance-rg01";
#Connecting to the Azure VM using the Service Principle
$pscredential = New-Object -TypeName System.Management.Automation.PSCredential($AzureApplicationID, $password);
Connect-AzAccount -ServicePrincipal -Tenant $AzureDirectoryID -Credential $pscredential | Out-null;
#List all the Load Agents
$VMList = Get-AzVm -ResourceGroupName $LoadAgentResourceGroup -Status;
ForEach($VM in $VMList) {
#Skipping the Master Machine and DB machine
if ($VM.Name -eq "test-load-appmachine01" -or $VM.Name -eq "test-load-appmachine02") {
continue;
}
$VMLoadAgentStatus = (Get-AzVm -ResourceGroupName $LoadAgentResourceGroup -Name $VM.Name -status).Statuses
$CurrentLoadAgentRunningStatus = $VMLoadAgentStatus[1].DisplayStatus;
if($CurrentLoadAgentRunningStatus -match "deallocated" -or $CurrentLoadAgentRunningStatus -match "VM deallocated"){
Start-AzVM -ResourceGroupName $LoadAgentResourceGroup -Name $VM.Name | Out-null
commandVerifier;
checkVMStatus($VM.Name);
}
else {
Write-Host $VM.Name " Current State is "$CurrentLoadAgentRunningStatus;
}
}
}
function commandVerifier() {
if ($?){
Write-Host "Successfully Started "$VM.Name;
}
else {
Write-Host "Start Unsuccessful "$VM.Name;
}
}
function checkVMStatus($VM_NAME) {
$VMLoadAgentStatus = (Get-AzVm -ResourceGroupName $LoadAgentResourceGroup -Name $$VM_NAME -status).Statuses
$VMRunningStatusAfterTriggered = $VMLoadAgentStatus[1].DisplayStatus;
if($VMRunningStatusAfterTriggered -eq "running" -or $VMRunningStatusAfterTriggered -eq "VM running"){
Write-Host "Successfully Started VM"
}
else{
Write-Host "Something went with starting VM and current status is"$VMRunningStatusAfterTriggered
}
}
function getServicePrincipleDetails () {
$AzuresecretValue = "<secretValue>";
$AzureApplicationID = "<app_id>";
$AzureObjectID = "<obj_id>";
$AzureDirectoryID = "<dir_id>";
$AzureUserName = "SVCUSER";
$AzureSubscriptionID = "<sub_id>";
restartLoadAgents $AzuresecretValue $AzureApplicationID $AzureObjectID $AzureDirectoryID $AzureUserName $AzureSubscriptionID
}
getServicePrincipleDetails
There are 5 VM in total and first two need not to be stopped or started. test-load-appmachine03,test-load-appmachine04 & test-load-appmachine05 are the target VM and I want to start them parallelly and check after.

Get running VMs on Azure

I have the below code to check daily if all the VMs that are meant to auto-start have started successfully.
$Date = (Get-Date -Format "dd-MM-yyyy HH-mm").toString()
$Results = "C:\temp\DailyChecks_$($Date).txt"
$Cred = get-credential -UserName 'AZ-User'
Connect-AzAccount -Tenant 'TenantID' -credential $Cred | out-null
$fCount = (Get-AzVM -Status | Where-Object { $_.tags['Managed By'] -like 'Manager' }).count
do {
$rCount = (Get-AzVM -Status | Where-Object { $_.tags['Managed By'] -like 'Manager' -and $_.PowerState -eq 'VM Running' }).count
if($rCount -lt $fCount)
{
write-host "There are $rCount VMs running, checking again"
}
elseif($rCount -eq $fCount){write-host "There are $rCount VMs running, exiting loop"}
}until($fCount -eq $rCount)
Get-AzVM -Status | Where-Object { $_.tags['Managed By'] -like 'Manager' } |
Select-Object Name, PowerState | Format-Table | out-file $Results
I have a couple of questions:
Is there a better way to write this code?
How can I check if the code has been running for longer than 30 minutes and yet not all VMs are running?
You can determine for how much the time the script is running by using a StopWatch object.
$sw = [System.Diagnostics.Stopwatch]::new()
$sw.Start()
Whenever you want, just check the elapsed time by checking the elapsed property
$sw.Elapsed
$sw.Elapsed.TotalSeconds
Write-Host "Time elapsed: $([Math]::Round($sw.Elapsed.TotalMinutes,0)) min $($sw.Elapsed.Seconds) seconds"

How to use powershell to wait for an action to complete

I have a script to start VMs/Stop them at a specific time. The issue is, I want the script to only exit when all the VMs are started/running or when they are deallocated/stopped. My current problem is when a VM is starting, it waits until it has started before moving to the next one.
eg: vm1 is starting..
vm2 is starting..
vm3 is starting..
vm1 is now running..
vm2 is still starting
vm3 is still starting
vm1 is now running..
vm2 is now running..
vm3 is now running..
Then script exits.
Full script here
$ACTION="start"
Write-Output "Number of Virtual Machines: $($GetVMS.Name.Count)" `n
$GetVMS | Format-Table
$startstopvm = {
$ResourceGroupName = $args[0]
$Name = $args[1]
$ACTION = $args[2]
# Get VM status
try {
$VMs = Get-AzureRmVM -Name $Name -ResourceGroupName $ResourceGroupName -Status -WarningAction SilentlyContinue
} catch {
Write-Output ("Cloud not get vm $Name in $ResourceGroupName")
$Error[0]
Exit 1
}
if ($ACTION -eq "start")
{
foreach ($VM in $VMs)
{
if ($VM.Statuses[1].Code -eq "PowerState/running")
{
Write-Output ($VM.Name + " in " + $VM.ResourceGroupName + " is already running")
}
else
{
# The VM needs to be started
Write-Output ("Starting VM " + $VM.Name)
$startVM += Start-AzureRmVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName -AsJob -ErrorAction Continue
$startTime = Get-Date
$timeElapsed = $((Get-Date) - $startTime).TotalMinutes
while ($timeElapsed -lt 2)
{
$startVM = Get-AzureRmVM -Name $VM.Name -ResourceGroupName $VM.ResourceGroupName -Status -WarningAction SilentlyContinue
if ($startVM.Statuses[1].Code -match "PowerState/(running|starting)")
{
# The VM started, so send notice
Write-Output ($VM.Name + " in " + $VM.ResourceGroupName + " has been started`n")
break
}
Start-Sleep -s 30
}
if ($getStat.Statuses[1].Code -ne "PowerState/(running|starting)")
{
# The VM failed to start, so send notice
Write-Output ($VM.Name + " failed to start`n")
}
}
}
}
NOTE: I am reading the VM name & RG from a file
try {
$VMList = Get-Content C:\Users\local\Desktop\VMs.csv | ConvertFrom-Csv
} catch {
Write-Output ("Cannot open file...")
exit -1
}
$Result = #()
foreach ($vm in $VMList) {
Invoke-Command -ArgumentList $vm.ResourceGroupName, $vm.Name, $ACTION -Verbose -ScriptBlock $startstopvm
}
The simplest way I have done this in the past is to use the -Wait parameter on a Start-Process cmdlet.
You should be able to implement this with small changes.
Saving your current code block into a seperate .ps1 i.e. startstopvm.ps1
You could then change the Invoke-Commmand line to read something like:
Invoke-Command -ArgumentList $vm.ResourceGroupName, $vm.Name, $ACTION -Verbose -ScriptBlock {Start-Process powershell.exe -Argument "C:\Scripts\Backup.ps1 TestBackup" -Wait}
Definitely some other ways to do it but an approach like this has always worked for me

How to use PowerShell parameter in Jenkins

I am using PowerShell to automate VM start/stop in Azure. However, when I set the $OPTION parameter it doesn't do anything. I have if/elseif/else statements.
See code below:
Add-AzureRmAccount -Credential $psCred -TenantId <removed> -ServicePrincipal
Get-AzureRmSubscription -SubscriptionName "<removed>"
#Get VMs using Tags
$vms = (Find-AzureRmResource | Where-Object {($_.tags.Project -eq "DevOps") -And ($_.tags.Test -eq "ernest")} | Select Name, ResourceGroupName)
$vms
Write-Output "Number of Virtual Machines: $($vms.Name.Count)"
foreach($VM in $vms)
{
if ($OPTION -eq "start" -And $VM.ResourceType -eq "Microsoft.Compute/virtualMachines")
{
Write-Output "Starting :- $VM.Name in $VM.ResourceGroupName"
Start-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Verbose
Write-Output $VM.Name "has started successfully"
Write-Output "Writing output to workspace"
Get-AzureRmVM -Status | Where-Object {($_.tags.Project -eq "DevOps") -And ($_.tags.Test -eq "ernest")} | Select Name, ResourceGroupName, PowerState > VM_Start_Info-$(get-date -f yyyy-MM-dd).tsv
}
elseif ($OPTION -eq "stop" -And $VM.ResourceType -eq "Microsoft.Compute/virtualMachines")
{
Write-Output "Deallocating :- $VM.Name in $VM.ResourceGroupName"
Stop-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Force -Verbose
Write-Output $VM.Name "has been deallocated successfully"
Write-Output "Writing output to workspace"
Get-AzureRmVM -Status | Where-Object {($_.tags.Project -eq "DevOps") -And ($_.tags.Test -eq "ernest")} | Select Name, ResourceGroupName, PowerState > VM_Stopped_Info-$(get-date -f yyyy-MM-dd).tsv
}
else
{
Write-Output "No option selected, select an option"
}
}
Write-Output "Script complete"
I had to add the $env:OPTION parameter to the Execute Powershell window. It works now

Resources