Get Last member of array in PowerShell

This should be easy, no? I learnt a new method for getting last member of array in PowerShell last week. Up until, I used to get the count of array members, subtract 1 from it (as you know, index starts with 0) and then get that element of array:

PS C:\Users\mgoyal> $newArray = @(“one”,”two”,”three”,”four”,”five”)
PS C:\Users\mgoyal> $lastmember = $newArray[$newArray.Count – 1]
PS C:\Users\mgoyal> $lastmember
five

In place of above, we can also use this:

PS C:\Users\mgoyal> $newArray[-1]
five

Not only this, we can also get last 2nd, or 3rd element like that. The idea is that you can use negative index to get elements of array and it starts with -1 and backwards.

 

4 thoughts on “Get Last member of array in PowerShell

  1. I would like to list the all webapps in a resource group and list the app settings for all of them(basically would like to create a array of webapps). I tried below script but it doesn’t work. any help is appreciated
    $resourcegroupname= ‘sam’
    $Sites = Get-AzureRmResource -ResourceGroupName $resourcegroupname -ResourceType “Microsoft.Web/sites”
    foreach ($site in $sites){
    $site.SiteConfig.AppSettings }

    Like

    • When you get an array or webapps you don’t get the full object. You have to get the individual resource again within the loop and then you can access all app settings.

      get-azwebapp -ResourceGroupName $resourceGroupName | % {
      (get-azwebapp -ResourceGroupName $resourceGroupName -Name $_.Name).SiteConfig.AppSettings
      }

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s