Azure Runbook - Job could not be stopped - azure

I have a PowerShell Azure Runbook in a Running state.
Pressing Stop via the Azure Portal results in an error message:
"Job could not be stopped".
Using the PowerShell cmdlet Stop-AzureRMAutomationJob results in the error message:
"InternalServerError: {"Message":"An error has occurred."}
From the documentation it looks like the job will be stopped after 3hrs, but is there any other way to stop a Runbook job or deal with a situation like this?

This issue went to the Microsoft product group to fix and should be fixed now.

first u should find the job ID with failed status...
Get-AzureRmAutomationJob -ResourceGroupName $RG -AutomationAccountName $AA | where {$.RunbookName -eq "runbook name" -and $.status -eq "Failed"}
then after stop the runbook
Stop-AzureRmAutomationJob -ResourceGroupName $RG -AutomationAccountName $AA -id JOBID

Related

Powershell Foreach-Object parallel with az cli profile isolation

I have a script that need to call child scripts in parallel. Child scripts using az cli and create/modify Azure PaaS objects in different Azure subscriptions. The problem is that as different scripts are using az account set --subscription <subscription-for-script>, they overlap and something that need to be created in subscription A by script A, created in subscription B cause a moment before script B set subscription to subscription B.
As az cli stores context in AzureProfile.json, I tried to create new folder per script and via $Env:AZURE_CONFIG_DIR specify different values per script. But I cannot find a way to isolate environment variables in child scripts, or specify AzureProfile context without using environment variables.
In parent script:
$listOfScripts | Foreach-Object -Parallel {
<block to run script with arguments>
} -AsJob -ThrottleLimit 50
and in each child script:
$Env:AZURE_CONFIG_DIR = "$RootPath\..\AzureProfiles\folderForScript"
az login --service-principal -u ${env:ARM_CLIENT_ID} -p ${env:ARM_CLIENT_SECRET} --tenant ${env:ARM_TENANT_ID}
az account set --subscription $subscription_id
Would be appreciate for advice how could be achieved running parallel independent scripts that uses different subscriptions to modify Azure PaaS objects
Update: Only solution that found - not to use az login and az account set inside scripts that run in parallel. Just connect via SPN in parent script and use parameter --subscription in each az command.
Run script block in parallel
Script blocks run in a runspace context in a PowerShell. It contains all the defined variables, functions & loaded modules. Initializing a runspace for script to run in takes time and resources. It must be run within their own runspace when scripts are running in parallel. Each runspace must load whatever module is needed and have any variable be explicitly passed in from the calling script.
The only variable that automatically appears in the parallel script block is the piped in object. Other variables are passed in using the $using: keyword.
Example
$computers = 'computerA','computerB','computerC','computerD'
$logsToGet = 'LogA','LogB','LogC'
# Read specified logs on each machine, using custom module
$logs = $computers | ForEach-Object -ThrottleLimit 10 -Parallel {
Import-Module MyLogsModule
Get-Logs -ComputerName $_ -LogName $using:logsToGet
}
References
PowerShell ForEach-object -parallel Feature
SO Thread for implementation

Execute commands in elevation powershell

I am running a Node.JS app that is executing some powershell commands to set the DNS services for my WiFi interface.
Unfortunately, the script fails without admin permissions, so I am trying to elevate the script within node.js
Start-Process -FilePath powershell.exe -ArgumentList {
Write-Host "Hello"
Set-DnsClientServerAddress -InterfaceIndex 10 -ServerAddresses ("127.0.0.1", "8.8.8.8")
sleep 5
} -verb RunAs
For some reason, this isn't applying the changes, despite the script outputting "hello" and waiting for 5 seconds. Does anyone know why that might be?

If azure VM is idle for 30 minutes I need to shut it down

If an azure VM is idle for 30 minutes I need to shut it down. By idle I mean CPU percent is less than 30%. How can I achieve this?
I have tried with run books default functions but it has shutdown and start but not with idle time.
Try this by Powershell , you can run this command as a scheduled job based on your requirement :
$vm = Get-AzureRmVM -Name <your vm name> -ResourceGroupName <your resource group name>
$current = Get-Date
#get cpuMetrics for each minute in past 30 mins
$cpuMetrics = Get-AzureRmMetric -ResourceId $vm.Id -TimeGrain 00:01:00 -StartTime $current.AddMinutes(-30) -EndTime $current -DetailedOutput -MetricNames "Percentage CPU"
$CPUUsangeRange = ($cpuMetrics.Data | select Average).Average | measure -Maximum
#get Maximum value of cpu usage percentage in past 30 mins, if the Maximum value less than 30% ,its idle and stop it .
if($CPUUsangeRange.Maximum -lt 30){
Stop-AzureRMvm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force
}
Sometimes you cannot get last 2 or 3 mins cpu Metrics data as there will be some latency.

Trying to use Azure Custom Script Extension to run a background job or a powershell task scheduler

Hi after my vm gets created I run the Azure Custom Script Extension which runs a powershell script. So the script does some basic tasks like create a share create some files and creates a powershell script and stored it on the vm. the last step in the custom vm extension script I have it attempt to setup a task scheduler job to call a powershell script that was created above and the script should end fromt he extension.
The problem isthe extension gets stuck in a running state and never stops. I wrote a log to find out the progress of the script and it shows it went through the whole script fine but it gets stuck in running and the task scheduler script does not run the job.
When i log in the vm manually I ran the script manually and it works fine. So I am not sure what is causing it to hang and what user it is running as the vm extension that is.I tried to run a powershell background job instead of the scheduler and I got the same symptoms above.
The below code is the task scheduler I tried to run the vm custom extension that does not work when trying to set it up through the custom extension but runs fine manually setup from the vm.
$jobname = "MasterFileWatcher"
$script = "c:\test\MasterFileWatcher.ps1"
$repeat = (New-TimeSpan -Minutes 1)
$action = New-ScheduledTaskAction –Execute "$pshome\powershell.exe" -Argument "$script; quit"
$duration = ([timeSpan]::maxvalue)
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -
RepetitionInterval $repeat -RepetitionDuration $duration
$msg = "Enter the username and password that will run the task";
$credential = $Host.UI.PromptForCredential("Task username and
password",$msg,"$env:userdomain\$env:username",$env:userdomain)
$username = $credential.UserName
$password = $credential.GetNetworkCredential().Password
$username = "$env:userdomain\testuser"
$password = "testpass"
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable -DontStopOnIdleEnd
Register-ScheduledTask -TaskName $jobname -Action $action -Trigger $trigger -RunLevel Highest -User $username -Password $password -Settings $settings
I found out the issue.
I had to set the username as system so the task scheduler could run as Localsystem account
Register-ScheduledTask -TaskName $jobname -Action $action -Trigger $trigger -RunLevel Highest -User "System" -Settings $settings

Can I use PowerShell instead of AppCmd.exe to monitor IIS state?

I want to write a script that uses appcmd.exe to monitor IIS state -
restart a site if it's down and/or restart IIS if it's down.
Can this be done with powershell? is there a more natural/easier method of doing this?
Thanks :-)
Windows PowerShell is always the Answer! This should do it for your particular question:
# Cycle IIS if it's not running
Get-Service W3SVC |
Where-Object {$_.Status -ne 'Running' } |
Start-Service
Import-Module WebAdministration
# Cycle websites that are not started
Get-Website |
Where-Object { $_.State -ne 'Started' } |
ForEach-Object { $_.Start() }
Hope this Helps
You can use the WebAdministration module to do it in a more elegant way than using appcmd.
http://technet.microsoft.com/en-us/library/ee790599.aspx

Resources