0
votes

My requirement is to delete snapshots that are older than 7 days with the name like appname-. but before deleting i need to fetch the snapshot data with some names. the script executes and provides some snapshot datas inidtially but in middle thhows below error. could someone help me on this.why i got this error message and how to fix

=========================================================================

Get-AzSnapshot : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'ResourceGroupName'. Specified method is not supported. At line:6 char:39 + Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotNam ... + ~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Get-AzSnapshot], ParameterBindingException

+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.Azure.Commands.Compute.Automation.GetAzureRmSnapshot

$snapshotnames = (Get-AzSnapshot).Name

foreach($snapname in $snapshotnames)
{
    $resourceGroupName = (Get-AzResource -Name $snapname).ResourceGroupName
    Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapname  | Where-Object {($_.TimeCreated -eq (Get-Date).AddDays(-3))} <#-and ($_.Name -like '*-2019_*') } | select Name,TimeCreated -Verbose 

}
1
Does Get-AzResource -Name $snapname ever result in multiple items? If that happens, then $resourceGroupName will become an object array. Then you will have this problem.AdminOfThings
i want the $resourceGroupName variable to hold ResourceGroup names value. How can i convert the object array variable to string of values?Jayanth .R
will piping $resourcegroup variable to Out-String resolves this issue? Like below $resourceGroupName | Out-StringJayanth .R
$snapshotnames = (Get-AzSnapshot).Name foreach($snapname in $snapshotnames) { $rg = (Get-AzResource -Name $snapname).ResourceGroupName $resourceGroupNames = $rg | out-string foreach($resourceGroupName in $resourceGroupNames){ Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapname | Where-Object {($_.TimeCreated -lt (Get-Date).AddDays(-6)) -and ($_.Name -like 'apr-2019_') } | select Name,TimeCreated } }Jayanth .R
I guess no. Piping to Out-String will through an error as below Get-AzSnapshot : Unexpected character encountered while parsing value: <. Path '', line 0, position 0. At line:10 char:9 + Get-AzSnapshot -ResourceGroupName $resourceGroupName -Snapsho ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [Get-AzSnapshot], JsonReaderException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.Automation.GetAzureRmSnapshotJayanth .R

1 Answers

0
votes
(Get-AzResource -Name $snapname).ResourceGroupName

This will return a collection of Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResource objects, each of which have the ResourceGroupName property. You need to add logic to filter the $resourceGroupName variable to only contain the one you are looking for.