简体   繁体   中英

Creating Web Bindings from a string with multiple entries using PowerShell

I'm new to PowerShell and already facing a big challenge. The goal is to read a csv file. Each row of the file will be a string with binding parameters like:

"Website1","116.167.74.172:443:www.xyz.com
116.167.74.174:443:www.xyz.com"

"Website2",":80:www.xyz.com 116.167.74.172:80:"

"Website3","116.167.75.155:443: 116.167.75.163:443:"

"Website4",":80:"

The command to be used is:

New-WebBinding -Name "Default Web Site" -IPAddress "*" -Port 80 -HostHeader TestSite

The problem is: how do I read the one string and break it into 3 parameters: IP , Port and HostHeader , even when I don't have all the 3 parameters specified?

You can use a regex with named capture groups to make this easier. Let me suggest that you always put the port to the right of the ip address, if there is an ip address. Then the following will do what you are looking for, assuming that a given line of the file is currently in $strLine.

$pattern = '"[^"]+","(?<ip_address>(?:\d{1,3}\.){3}\d{1,3})?:?(?<port>\d{1,5})?:?(?<hostheader>.*)?'  
$strLine -match $pattern  
$ipaddress = if ($matches.ContainsKey('ip_address')) { $matches['ip_address'] } else { "*" }  
$port = if ($matches.ContainsKey('port')) { $matches['port'] } else { "80" }  
$hostheader = if ($matches.ContainsKey('hostheader')) { $matches['hostheader'] } else { "TestSite" }  

New-WebBinding -Name "Default Web Site" -IPAddress $ipaddress -Port $port -HostHeader $hostheader 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM