Posted On December 26, 2019

PowerShell: Working With Arrays

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Working With Arrays

Problem: elements of a System.Array couldn’t be counted

# Example output when an object is a Hashtable type
PS C:\Users\tola> $arr.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object

Resolution: convert a Hashtable to an Array type

# Perform explicit casting
PS C:\Users\tola> $x=[Array]$arr

# Example output when an object is an Array type
PS C:\Users\tola> $arr.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array

# Validate that the casting has succeeded
PS C:\Users\tola> $x.gettype()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array

# Since System Array type can contain objects, its elements can be counted
PS C:\Users\tola> $x.count
1

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

Find Hostnames per UserID in Event Logs on Domain Controllers

$targetAccounts=Get-Content "C:\Users\kimconnect\Desktop\targetAccounts.txt"function Get-UserComputerName { <#.SYNOPSIS Searches a specified Domain Controller for the computername of a…

PowerShell: Split Array into Multiple Sub-Arrays and Inflate Strings to Certain Lengths to Create Visual Columns

What does a nerd do on his free time? Give himself little puzzles to solve.…

PowerShell: Alternative to Test-NetConnection for Legacy Windows

This little snippet is useful as a helper function to quickly determine port connectivity between…