Jee
Jee

Reputation: 71

PowerShell: Use One of Multiple Values from an Output

I was able to get the IP addresses of the DNS servers configured for my computer using the ff:

$DNSServers = Get-DnsClientServerAddress -InterfaceAlias "Ethernet" | select -expand ServerAddresses

The output contained two distinct IP address values. How can I extract and use one of those values as the value for a variable to be used for an LDAP query in AD?

For example, if the output for the above code is 192.168.10.101 172.16.100.201, I should be able to pass either of those IP address values to the variable for the code for my LDAP query.

Upvotes: 0

Views: 2381

Answers (1)

mjsqu
mjsqu

Reputation: 5452

Ascertaining the data type

The command you've written returns an array. You can see this by passing it to Out-GridView:

$DNSServers | Out-GridView

or checking the type:

$DNSServers.GetType()

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

Accessing data

Arrays can be accessed by index:

$DNSServers[0]
$DNSServers[1]
etc...

It's important to note that the array indexing starts at zero, not 1.

For Each loop

In a loop:

ForEach ($server in $DNSServers) {
    # Do something with server
    $server
}

For loop with iteration

Or by index in a loop, using the Array's Count property:

for ($i = 0; $i -lt $DNSServers.Count; $i++)
{ 
    $DNSServers[$i]
}

Piping

You can also pipe the object into a For Each, the shorthand notation for this is %. Each element in the loop is assigned the internal variable $_:

$DNSServers | % {
    # Do something with server ($_)
    $_
}

This is not as readable, but handy if you're just writing a quick script for one-off use.

Tip: If you hit Ctrl+J in Powershell ISE, you'll bring up the snippets menu, which contains prebuilt for loop syntax, of both types specified here. However, be careful, as the for snippet starts at $i = 1, so you need to change it when using it with arrays.

Upvotes: 3

Related Questions