Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an IIS IP address in string format from Get-WebBinding in Powershell

Tags:

powershell

iis

I am trying to retrieve the IP address of a website that I am referencing via the ID (vs. the name). The best way I can figure out to do it is using a regex on the "bindingInformation" property going up to the first colon as below...

$siteID = "22"
$website = Get-Website | Where { $_.ID -eq $siteID }
$iP = Get-WebBinding $website.name | Where { $_.bindingInformation -match "/[^:]*/" }

However it doesn't seem to be populating the $iP variable?

As I step through I get this:

PS IIS:\sites> Get-WebBinding $website.name

protocol  bindingInformation                                                                        
-------- ------------------                                                                        
http      10.206.138.131:80:                                                                        
http      10.206.138.131:80:dev1.RESERVED22                                                         
http      10.206.138.131:80:dev1.www.RESERVED22 

I guess what I'm not sure about is how to convert the $_.bindingInformation into a string format variable? Pretty new to Powershell so sorry if this seems simple. I need the $IP variable to be "10.206.138.131" in this example... Thank you for any help.

like image 327
Dominic Brunetti Avatar asked Mar 14 '23 09:03

Dominic Brunetti


1 Answers

You can use Select-Object -ExpandProperty bindingInformation to grab just the bindingInformation property value:

PS C:\> Get-WebBinding "sitename" |Select-Object -ExpandProperty bindingInformation
10.206.138.131:80:
10.206.138.131:80:dev1.RESERVED22
10.206.138.131:80:dev1.www.RESERVED22

Now, since each binding string is in the form:

[IP]:[Port]:[Hostname]

We can use the -split operator to split it into 3 and just grab the first one:

PS C:\> $Bindings = Get-WebBinding "sitename" |Select-Object -ExpandProperty bindingInformation
PS C:\> $Bindings | ForEach-Object { @($_ -split ':')[0] }
10.206.138.131
10.206.138.131
10.206.138.131

Finally, you can use Sort-Object -Unique to remove all duplicates:

PS C:\> $Bindings = Get-WebBinding "sitename" |Select-Object -ExpandProperty bindingInformation
PS C:\> $IPs = $Bindings | ForEach-Object { @($_ -split ':')[0] }
PS C:\> $IPs = @($IPs |Sort-Object -Unique)

The $IPs variable is now an array containing all the distinct IP addresses used for bindings, in your case just a single one:

PS C:\> $IPs
10.206.138.131
like image 64
Mathias R. Jessen Avatar answered Apr 14 '23 17:04

Mathias R. Jessen