问题描述
我正在使用 Powershell 在 Web 服务器上设置 IIS 绑定,但在使用以下代码时遇到问题:
I'm using Powershell to set up IIS bindings on a web server, and having a problem with the following code:
$serverIps = gwmi Win32_NetworkAdapterConfiguration
| Where { $_.IPAddress }
| Select -Expand IPAddress
| Where { $_ -like '*.*.*.*' }
| Sort
if ($serverIps.length -le 1) {
Write-Host "You need at least 2 IP addresses for this to work!"
exit
}
$primaryIp = $serverIps[0]
$secondaryIp = $serverIps[1]
如果服务器上有 2 个以上的 IP,那很好 - Powershell 返回一个数组,我可以查询数组长度并提取第一个和第二个地址就好了.
If there's 2+ IPs on the server, fine - Powershell returns an array, and I can query the array length and extract the first and second addresses just fine.
问题是 - 如果只有一个 IP,Powershell 不会返回单元素数组,而是返回 IP 地址(作为字符串,如192.168.0.100") - 该字符串具有 .length
属性,它大于 1,所以测试通过,我最终得到字符串中的前两个字符,而不是集合中的前两个 IP 地址.
Problem is - if there's only one IP, Powershell doesn't return a one-element array, it returns the IP address (as a string, like "192.168.0.100") - the string has a .length
property, it's greater than 1, so the test passes, and I end up with the first two characters in the string, instead of the first two IP addresses in the collection.
如何强制 Powershell 返回单元素集合,或者确定返回的事物"是否是对象而不是集合?
How can I either force Powershell to return a one-element collection, or alternatively determine whether the returned "thing" is an object rather than a collection?
推荐答案
通过以下两种方式之一将变量定义为数组...
将您的管道命令用@
开头的括号括起来:
Wrap your piped commands in parentheses with an @
at the beginning:
$serverIps = @(gwmi Win32_NetworkAdapterConfiguration
| Where { $_.IPAddress }
| Select -Expand IPAddress
| Where { $_ -like '*.*.*.*' }
| Sort)
将变量的数据类型指定为数组:
Specify the data type of the variable as an array:
[array]$serverIps = gwmi Win32_NetworkAdapterConfiguration
| Where { $_.IPAddress }
| Select -Expand IPAddress
| Where { $_ -like '*.*.*.*' }
| Sort
或者,检查变量的数据类型...
IF ($ServerIps -isnot [array])
{ <error message> }
ELSE
{ <proceed> }
这篇关于当调用仅返回一个对象时,如何强制 Powershell 返回数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!