Iis 使用PowerShell从包含多个条目的字符串创建Web绑定

Iis 使用PowerShell从包含多个条目的字符串创建Web绑定,iis,powershell,Iis,Powershell,我是PowerShell的新手,已经面临着巨大的挑战。 目标是读取csv文件。文件的每一行都将是一个具有绑定参数的字符串,如: 网站1116.167.74.172:443:www.xyz.com 116.167.74.174:443:www.xyz.com 网站2:80:www.xyz.com 116.167.74.172:80: 网站3116.167.75.155:443:116.167.75.163:443: 网站4:80: 要使用的命令是: New-WebBinding -Name "De

我是PowerShell的新手,已经面临着巨大的挑战。 目标是读取csv文件。文件的每一行都将是一个具有绑定参数的字符串,如:

网站1116.167.74.172:443:www.xyz.com 116.167.74.174:443:www.xyz.com

网站2:80:www.xyz.com 116.167.74.172:80:

网站3116.167.75.155:443:116.167.75.163:443:

网站4:80:

要使用的命令是:

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

问题是:即使我没有指定所有3个参数,如何读取一个字符串并将其分解为3个参数:IP、Port和HostHeader?

您可以使用带有命名捕获组的正则表达式来简化这一过程。如果有ip地址,我建议您始终将端口放在ip地址的右侧。然后,假设文件的给定行当前在$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 

I get:无法索引到空数组中。第1行字符:1+$ipaddress=如果$matches['ip地址]].Length-gt 0{$matches['ip地址]]}…+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~CategoryInfo:InvalidOperation::[],RuntimeException+FullyQualifiedErrorId:NullArray