aws / aws-tools-for-powershell

The AWS Tools for PowerShell lets developers and administrators manage their AWS services from the PowerShell scripting environment.
Apache License 2.0
243 stars 80 forks source link

AWS Powershell Get-SSMMaintenanceWindowsTargets #11

Closed magrossm closed 5 years ago

magrossm commented 5 years ago

Dear All,

I have following function

function Get-SSMMaintenanceWindowMatch ($instance) {
  $mws = (Get-SSMMaintenanceWindowList -Region eu-west-1).WindowId
  for ($i=0; $i -le $mws.Length; $i++)  {
        $val = ((Get-SSMMaintenanceWindowTargets -region eu-west-1 -WindowId $mws[$i]).Targets).Values
        if (($val -eq $instance) {
        return $instance
        else {
        return $null
             }

      }
   }
}

The problem is that sometimes $val equals $null because the .Values in JSON are not existentn.

I get following error.

PS C:\WINDOWS\system32> Get-SSMMaintenanceWindowMatch $instanceId
Get-SSMMaintenanceWindowTargets : 1 validation error detected: Value null at 'windowId' failed to satisfy constraint: Member must not be 
null
At line:4 char:18
+ ...    $val = ((Get-SSMMaintenanceWindowTargets -region eu-west-1 -Win ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (Amazon.PowerShe...owTargetsCmdlet:GetSSMMaintenanceWindowTargetsCmdlet) [Get-SSMMaintenan 
   ceWindowTargets], InvalidOperationException
    + FullyQualifiedErrorId : Amazon.SimpleSystemsManagement.AmazonSimpleSystemsManagementException,Amazon.PowerShell.Cmdlets.SSM.GetSSMMa 
   intenanceWindowTargetsCmdlet

Any ideas? It works if an istance itself is registered to a maintenance window as a target but i want the loop to work if a member of the resulting array is null.

matteo-prosperi commented 5 years ago

According to the underlying API documentation, windowId is a required parameter, so a failure in using the cmdlet with a $null value is expected. Could you just exclude nulls from your list?

$mws = (Get-SSMMaintenanceWindowList -Region eu-west-1).WindowId | Where { $null -ne $_ }
ForEach ($item in $mws)
{