Array items are referred to as elements. Although array elements can be of different data types, in most practical use cases, they’re all of the same type.

Referencing array elements

Array elements are referred to by their order in the array where the first element in the array is order #0. They follow the array variable enclosed in square brackets [ ] as in:

In this example, $b[2] refers to the third element of the array which has the value of 4

The last element in an array is number -1, the element before last is -2, the 2nd element from the end is -3, …

We can reference more than one element of an array by using the comma (,), the range operator (..), or the plus sign (+)

In this array $c we have 10 random numbers each is between 0 and 9:

The comma ‘,’ is used to separate multiple array elements. For example to reference the 3rd and 6th elements of the array we use $c[2,5] and we expect to get 1 and 4 values in this example.

The range operator ‘..’ is used to get a sequential range of elements. To get elements 4 through 7 we can use $c[3..6]

The range operator circles the array boundary. For example, $c[-2..2] will list the element before last [-2], the last element [-1], the first element [0], the second element [1], and the third element [2] in this order

Although not very practical, you can mix individual elements and ranges when referencing array elements. Ranges are to be preceded by the plus sign (+). Individual elements are to be preceded by the comma (,) except after a range where they must be preceded by the plus sign (+) as well:

What we see often in practical use of arrays:

Referencing one or more array elements separated by commas as $c[1,4,6]

Referencing a sequential range of array elements as $c[3..5]

Referencing the last array element $c[-1]

We often don’t know how many elements an array has. We can find that out by using $c.Count or $c.Length or $c.GetUpperBound(0)+1 or $c.GetLength(0). In our example, array $c has 10 elements.

Declaring a variable as an array

There are several ways to declare an array. The standard/default way is to let PowerShell figure it out.

In this example, PowerShell figured out that $d should be an array based on the data that we’re trying to store in it.

We can specify that by using the array sub-expression operator @(). This is particularly useful when we want to make sure a variable is an array

The reason is that on cycle 1 of this 4 cycle iteration, PowerShell auto-declared the variable $myList as a ‘System.ComponentModel.Component’ which is the object returned from the Get-Service cmdlet. We actually want $myList to be an array of such objects that can hold 0, 1, or more items. There are 2 ways to do this:

Declare $myList as an array upfront using the array sub-expression operator @()
or

Assign the resulting collection of the 4 cycle loop in one step instead of assigning each found value at the end of the if statement

The third way to declare an array is to type cast it. This only works in cases where all elements of the array are of the same data type. For example:

or

Here $myIPList is an array of objects, each is of data type ‘System.Net.IPAddress’

Removing array duplicates

Removing array duplicates is a simple matter of using ‘select -unique‘ as in:

Finding one or more values in an array

Finding a single value is a simple matter of using -match or -eq operators. For example:

In this example, the 8th and 10th elements have the value 3

Finding elements in array $a that also exist in array $b (AKA intersection of arrays $a and $b) can be done using ‘where’ statement and -in operator

This method produces the same result if the array elements are unique and sorted as in:

This example uses the array object .IndexOf() method to determine the first occurrence of the element with the 3 value. It then loops through the array elements using foreach and compiles a new array skipping the 8th element identified by $c.IndexOf(3), and reassigns this new array to variable $c

To remove the 4th and 8th array elements for example regardless of their values, we use an expression similar to:

This cmdlet/function takes a required parameter ‘Session’, which is of type ‘System.Management.Automation.Runspaces.PSSession’ that can be obtained via New-PSSession cmdlet of the ‘Microsoft.PowerShell.Core’ module.

It also takes 2 optional parameters that serve to filter its output:

-Layer3 parameter takes either ‘IPv4’ or ‘IPv6’ values or both, and will output only the records that match this criteria

-Layer4 parameter takes either ‘TCP’ or ‘UDP’ values or both, and will output only the records that match this criteria

In the course of automation, you might need to validate credentials that a script would use to perform a set of complex tasks before the script is run. The Validate-WindowsCredential and Validate-LinuxCredential PowerShell functions are two of the latest additions to the SB-Tools PowerShell module that simplify this task.

Validate-WindowsCredential

The Validate-WindowsCredential function/cmdlet takes 2 parameters:

‘Credential’ which is a PSCredential object that can be obtained from the Get-Credential cmdlet of the Microsoft.PowerShell.Security, or the Get-SBCredential function of the SB-Tools PS module.

‘Session’ which is a PSSession object that can be obtained via the New-PSSession cmdlet of the Microsoft.PowerShell.Core

Similarly, TRUE is returned if authentication is successful or FALSE if authentication fails.

It also displays additional information to the console such as the account hash.

Unlike the Validate-WindowsCredential cmdlet, the Validate-LinuxCredential cmdlet relies on reading and parsing the /etc/shadow file that has the hashes of user accounts of this Linux machine. The current revision of the cmdlet is designed to validate MD5 hashed accounts only. A possible enhancement is to add functionality to validate accounts hashed with other algorithms such as Blowfish and SHA

Have you been in the situation where you’re in a PS session trying to run commands against one or more remote computers using PowerShell Remoting sessions? You may have PS modules and cmdlets in the current PS session that are not available in the remote session(s). This function will allow you to export local PS session commands to remote PS sessions. The native Export-PSSession cmdlet seems to do the opposite – bringing remote session cmdlets to local PS session.

Export-SessionCommand PowerShell function is part of the SB-Tools PowerShell module. This function takes one or more Powershell script functions/commands from current session and exports them to a remote PS session. This function will ignore and not export binary functions. Exported functions will persist on the remote computer for the user profile used with the PS remote session.

The function takes the following parameters:

Command

This is a required parameter. This is one or more script commands available in the current PS session. For example Update-SmbMultichannelConnection cmdlet/function of the SmbShare PS module.
To see available script commands, you can use:

Get-Command | ? { $_.CommandType -eq 'function' }

ModuleName

This is an optional parameter that defaults to ‘SBjr’ if not provided. This is the name of the module that this function will create on the remote computer under the user profile of the remote PS session. This will over-write prior existing module with the same name.

Session

System.Management.Automation.Runspaces.PSSession object usually obtained by using New-PSSession cmdlet

I’ve added an additional parameter to allow passing a PSCredential object to this function/cmdlet. This is helpful when the user running the script/cmdlet does not have permissions on the target computer. Another enhancement in this update to to trap errors resulting from failure to WMI connect to the target computer like in case of ‘Access Denied’, or ‘RPC Server not available’ errors.

Get-SBWMI PowerShell function is part of the SB-Tools PowerShell module. It provides similar functionality to the native Get-WMIObject cmdlet with added option: Timeout.

The function takes 1 required parameter; ‘Class’. For example

Get-SBWMI Win32_computerSystem

will return output similar to:

It also accepts the following optional parameters:

Property

Property name of the provided ‘Class’ such as ‘NumberofLogicalProcessors’ property of the ‘Win32_computerSystem’ class:

Get-SBWMI Win32_computerSystem -Property NumberofLogicalProcessors

Filter

In the format Property=Value such as ‘DriveLetter=e:’

Get-SBWMI -Class Win32_Volume -Filter 'DriveLetter=e:'

ComputerName

Remote computer name or IP address

Get-SBWMI Win32_computersystem -ComputerName mgmt

NameSpace

The default is ‘root\cimv2’. To see name spaces type:

(Get-WmiObject -Namespace 'root' -Class '__Namespace').Name

TimeOut

In seconds. The default is 20.

This is a particularly helpful option especially if you’re in the situation of trying to query many hundreds or thousands of computers, where the vast majority respond quickly but few can drag out for several minutes or not respond at all causing the script to hang if using the native Get-WMIObject cmdlet.

Convert-IpAddressToMaskLength and Convert-MaskLengthToIpAddress PowerShell functions are two supporting functions in the SB-Tools PowerShell module that do what their names suggest.

These two functions come in handy when manipulating IPv4 addresses. For example, when adding/removing IPv4 address to/from a network interface using PowerShell during automated provisioning.

For example, the Get-NetIPAddress cmdlet of the NetTCPIP module, returns information similar to

Notice that the familiar dotted decimal subnet mask is missing. Instead we get ‘PrefixLength’ which is the number of bits that represent the network address out of the 32 bit IPv4 address. So, a 24 bit prefix means a 255.255.255.0 subnet mask.

The Convert-IpAddressToMaskLength function takes one or more dotted decimal subnet masks and returns the corresponding bit lengths. For example

Trying the new cmdlets, the Get-HCSControllerReplacementStatus cmdlet returns a message like:

The Get-HCSRehydrationJob returns no output (no restore jobs are running)

The Invoke-HCSDisgnostics seems pretty useful and returns output similar to:

The cmdlet takes a little while to run. In this case it took 14 minutes and 38 seconds:

It returns data from its several sections like;

System Information section:

This is output similar to what we get from the Get-HCSSystem cmdlet for both controllers.

Update Availability section:

This is output similar to Get-HCSUpdateAvailability cmdlet, although the MaintenanceModeUpdatesTitle property is empty !!??

Cluster Information section:

This is new exposed information. I’m guessing this is the output of some Get-HCSCluster cmdlet, but this is pure speculation on my part. I’m also guessing that this is a list of clustered roles in a traditional Server 2012 R2 failover cluster.

Service Information section:

This is also new exposed information. Get-Service is not an exposed cmdlet.

Failed Hardware Components section:

This is new exposed information. This device is in good working order, so this list may be false warnings.

Firmware Information section:

This output is similar to what we get from Get-HCSFirmwareVersion cmdlet

Network Diagnostics section:

Most of this information is not new, but it’s nicely bundled into one section.

Performance Diagnostics section:

Finally, this section provides new information about read and write latency to the configured Azure Storage accounts.

This script can be downloaded from the Microsoft Technet Gallery. It contains the Get-SBDisk function which takes one parameter as input being one or more computer names or IP addresses. It return s a PowerShell object for each fixed disk of each input computer.

To see the inline help and example:

help Get-SBDisk -ShowWindow

This script takes advantage of this function and collects disk information on all computers in the current AD domain (without the need to use ActiveDirectory PowerShell module):