How to delete managed disk snapshot every 10 minutes - azure

I have the below script which I am using in order to delete snapshot older then 10 minutes and retain the snapshot that are not older then 10minutes, I have the below script but its not working as it suppose to, can anyone tell me whats being going wrong?
foreach($snapname in $snapshotnames)
{
Get-AzureRmSnapshot -ResourceGroupName $rg -SnapshotName $snapname |?{$_.Name -Like "*-Server1*"} | ?{($_.TimeCreated).ToString('yyyyMMdd') -lt ([datetime]::Now.AddMinutes(-10).tostring('yyyymmdd'))} | remove-azurermsnapshot -force
}

You should use [datetime]::UtcNow instead of [datetime]::Now and not use .tostring('yyyymmdd').
So your command should be:
foreach($snapname in $snapshotnames)
{
Get-AzureRmSnapshot -ResourceGroupName $rg -SnapshotName $snapname | ?{$_.Name -Like "*-Server1*"} | ?{($_.TimeCreated) -lt ([datetime]::UtcNow.AddMinutes(-10))} | remove-azurermsnapshot -force
}
My specific test command:
Get-AzureRmSnapshot -ResourceGroupName "<ResourceGroupName>" -SnapshotName "<SnapshotName>" | ?{($_.TimeCreated) -lt ([datetime]::UtcNow.AddMinutes(-10))} | remove-azurermsnapshot -force
Result screenshot:

Related

Remove-AzAutomationSchedule needs confirmation, even with confirm parameter

I got a code collecting and deleting expired azure automation schedules
Connect-AzAccount -SubscriptionId "guidstuff"
$schedules = Get-AzAutomationSchedule -ResourceGroupName "resgrp" -AutomationAccountName "automationacc" | ?{$_.name -like "schedule1*" -and $_.expirytime -lt (get-date)}
$cache = Get-AzAutomationSchedule -ResourceGroupName "resgrp" -AutomationAccountName "automationacc" | ?{$_.name -like "schedule2*" -and $_.expirytime -lt (get-date)}
if($cache.count -ne 0){
$schedules += $cache
}
foreach($schedule in $schedules){
Remove-AzAutomationSchedule -Confirm:$false -AutomationAccountName $schedule.AutomationAccountName -ResourceGroupName $schedule.ResourceGroupName -Name $schedule.name
}
Its asking deletion-confirmation for every schedule, am I or is the CMDlet wrong ?
Its asking deletion-confirmation for every schedule, am I or is the CMDlet wrong ?
As suggested by #theo, we reproduced in our local environment by using the below cmdlet:
By default, -Confirm value is set to false only.
Remove-AzAutomationSchedule -AutomationAccountName 'tstautmation'-ResourceGroupName 'test-rg' -Name 'terer' -Confirm:$false -Force
Now, it will not ask for deletion-confirmation every time when we run the above command.
Refer this document for more information.

How can I simply get the powerstate from within a powershell workflow automation runbook in Azure?

I have a Powershell workflow runbook that automates starting and shutting down VMs in Azure, I updated the modules in an automation account (so I could use it for other things) and it has stopped the script working. I have fixed most of the broken stuff but the bit that is not now working is obtaining the power state eg: PowerState/deallocated so that it can be shutdown/started up. Here is my code:
$vmFullStatus = Get-AzureRmVM -ResourceGroupName test1 -Name test1 -Status
$vmStatusJson = $vmFullStatus | ConvertTo-Json -depth 100
$vmStatus = $vmStatusJson | ConvertFrom-Json
$vmStatusCode = $vmStatus.Statuses[1].code
Write-Output " VM Status Code: $vmStatusCode"
The Write-Output VM Status Code is now blank in the output of the runbook, but it outputs fine in standard shell. I only have limited experiences in workflow runbooks but I believe it needs to be converted to Json so the Workflow can use it.
I think the issue may lie with the statuses as when it is converted to Json it displays:
"Statuses": [
"Microsoft.Azure.Management.Compute.Models.InstanceViewStatus",
"Microsoft.Azure.Management.Compute.Models.InstanceViewStatus"
],
Which doesn't now show the PowerState. How can I get the powerstate of a vm from within a powershell workflow runbook so it can used? Thanks
I have tried an inline script and it does work if you specify a vm name:
$vmStatusCode = InlineScript {
$vmFullStatus = Get-AzureRmVM -ResourceGroupName test1 -Name test1 -Status
$vmStatusJson = $vmFullStatus | ConvertTo-Json -depth 100
$vmStatus = $vmStatusJson | ConvertFrom-Json
$vmStatus.Statuses[1].code
}
But it doesn't work when you pass variables:
$vmFullStatus = Get-AzureRmVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Status
Get-AzureRmVM : Cannot validate argument on parameter 'ResourceGroupName'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
it needs to be run without an inline script - any ideas?
forgot to add $using:
$vmStatusCode = InlineScript {
$vmFullStatus = Get-AzureRmVM -ResourceGroupName $using:vm.ResourceGroupName -Name $using:vm.Name -Status
$vmStatusJson = $vmFullStatus | ConvertTo-Json -depth 100
$vmStatus = $vmStatusJson | ConvertFrom-Json
$vmStatus.Statuses[1].code
}
This now works!

How to initialize a disk after I append a data disk to VM automatucally?

Based on this doc :
https://learn.microsoft.com/en-us/azure/virtual-machines/windows/attach-managed-disk-portal I can append a data disk to my windows Azure VMs and initialize the disk manually by login to the VM. Everything works for me.
BUT it is not enough as I want to make the whole process automatually by code. Could you please give me some code sample or guide about it ? Thanks!
#ShirazBhaiji provided a helpful doc that will meet your requirement, but there is a new feature that you can run commands on Azure VMs directly, no need to enable WinRM.
Just try the Powershell below :
This is the command to init a data disk in windows :
$disks = Get-Disk | Where partitionstyle -eq 'raw' | sort number
$letters = 70..89 | ForEach-Object { [char]$_ }
$count = 0
$labels = "data1","data2"
foreach ($disk in $disks) {
$driveLetter = $letters[$count].ToString()
$disk |
Initialize-Disk -PartitionStyle MBR -PassThru |
New-Partition -UseMaximumSize -DriveLetter $driveLetter |
Format-Volume -FileSystem NTFS -NewFileSystemLabel $labels[$count] -Confirm:$false -Force
$count++
}
Save it as a .ps1 file.
Use this command to append a disk and run the above command directly :
$vm = Get-AzVM -Name <your VM name> -ResourceGroupName <your vm resource group name>
$dataDiskName = $vm.Name + '_datadisk1'
$diskConfig = New-AzDiskConfig -SkuName 'Premium_LRS' -Location $vm.Location -CreateOption Empty -DiskSizeGB 128 -Zone 1
$dataDisk1 = New-AzDisk -DiskName $dataDiskName -Disk $diskConfig -ResourceGroupName $vm.ResourceGroupName
Add-AzVMDataDisk -VM $vm -Name $dataDiskName -CreateOption Attach -ManagedDiskId $dataDisk1.Id -Lun 1
Update-AzVM -VM $vm -ResourceGroupName $vm.ResourceGroupName
Invoke-AzVMRunCommand -VM $vm -CommandId 'RunPowerShellScript' -ScriptPath "<path of the previous .ps1 file>"
Result :
Hope it helps!
You can do this using powershell, you need to have windows remote management enabled on the VM.
Example scripts can be found here:
https://learn.microsoft.com/en-us/azure/virtual-machines/windows/attach-disk-ps

Read from txt file and convert to managed disks

I've got a list of virtua machines in Azure which I'm trying to convert to managed disks.
I have a list of vm's, I read from the list and export to csv capturing resourcegroupname and vm name, however I seem to get vms from the whole subscription.
Also when I attempt to import the csv, when I run $comps it returns the correct information in the csv, however I can't seem to pass them through to the next lines.
CSV format is
ResouceGroupName Name
RG-01 vm-01
RG-01 vm-02
RG-01 vm-03
RG-01 vm-04
The code I'm trying is
Login-AzureRmAccount
$sub = Get-AzureRmSubscription | ogv -PassThru
Select-AzureSubscription -SubscriptionId $sub
$virtualmachines = Get-Content C:\temp\vm.txt | % {
Get-Azurermvm | select ResourceGroupName,Name | export-csv c:\temp\vm.csv -NoClobber -NoTypeInformation -Append
}
$comps = Import-Csv c:\temp\Vm.csv |
foreach ($Comp in $comps)
{
Stop-AzureRmVM -ResourceGroupName $_.ResourceGroupName -Name $_.Name -Force
ConvertTo-AzureRmVMManagedDisk -ResourceGroupName $_.ResourceGroupName -VMName $_.Name
}
Thanks in advance..
For your issue, you export the virtual machines in a csv file and use it in the foreach code. So, it's unneccesary to use command:
$virtualmachines = Get-Content C:\temp\vm.txt | % {
Get-Azurermvm | select ResourceGroupName,Name | export-csv c:\temp\vm.csv -NoClobber -NoTypeInformation -Append
}
And your VMs all in a resourcegroup, you can get them with ResourceGroupName directly.
For the pipeline in foreach, it's unneccesary. You can use the following code that I make a little change with your code and it works well.
Login-AzureRmAccount
$sub = Get-AzureRmSubscription | ogv -PassThru
Select-AzureRmSubscription -Subscription $sub
Get-Azurermvm –ResourceGroupName RG-01 | select ResourceGroupName,Name | export-csv c:\temp\vm.csv -NoClobber -NoTypeInformation -Append
$comps = Import-Csv c:\temp\Vm.csv
foreach ($Comp in $comps)
{
Stop-AzureRmVM -ResourceGroupName $Comp.ResourceGroupName -Name $Comp.Name -Force
ConvertTo-AzureRmVMManagedDisk -ResourceGroupName $Comp.ResourceGroupName -VMName $Comp.Name
}
This is the screenshot of my result.

Is there an Azure powershell cmdlet to get cores, cpu of an ARM VM in a subscription

I am trying to get the list of ARM VM's in a subscription using Get-AzureRmVM and their instance sizes using the HardwareProfile.VmSize object. Is there a way to get the #of Cpu, #of Cores etc. for each vm using a cmdlet ( like in classic using the Get-AzureRoleSize cmdlet) ?
Do you mean use command to get information like this?
PS C:\User> $size = (Get-AzureRmVM -ResourceGroupName ubuntu -Name vm1).HardwareProfile.VmSize
PS C:\Users> get-azurermvmsize -location eastus | ?{ $_.name -eq $size }
Name NumberOfCores MemoryInMB MaxDataDiskCount OSDiskSizeInMB ResourceDiskSizeInMB
---- ------------- ---------- ---------------- -------------- --------------------
Standard_DS1_v2 1 3584 2 1047552 7168
Here the complete solution if you want to get the Total Cores of multiple VMs:
# Calculating total Amount of Cores
Write-Output "Calculating the total Cores of VMs ..."
try {
$TotalCores = $null
$Location = "westeurope"
$Cores = $null
$TotalVMs = (Get-AzVM -Status | Where-Object { $_.ProvisioningState -eq "Succeeded" }) | Sort-Object -Property Name
foreach ($VM in $TotalVMs) {
Write-Output "Checking $($Vm.Name) ..."
$VMSize = (Get-AzVM -Name $VM.Name).HardwareProfile.VmSize
$Cores = (Get-AzVMSize -location $Location | Where-Object { $_.name -eq $VMSize }).NumberOfCores
$TotalCores += $Cores
}
Write-Output "Wow! Found '$TotalCores' Cores ..."
}
catch {
$ErrorMsg = "[ERROR] while calculating the total CPU Cores: $($_.Exception.Message)!"
Write-Error -Message $ErrorMsg
}

Resources