关于powershell字符串split()的一个Q

关于powershell字符串split()的一个Q,powershell,powershell-2.0,Powershell,Powershell 2.0,我的脚本编写得很好 $item_name = $item["Server_Name"] $result = nslookup $item_name #a nslookup code to get the server's ip $split = $result.tostring() Caz直接使用split()将失败,所以我使用String(),但它显示为System.Object[] 如何从$result中提取内容调用可执行文件并将结果存储在变量中,将为您提供与输出“行”对应的字符串数组中的

我的脚本编写得很好

$item_name = $item["Server_Name"]
$result = nslookup $item_name #a nslookup code to get the server's ip
$split = $result.tostring()
Caz直接使用split()将失败,所以我使用String(),但它显示为System.Object[]


如何从$result中提取内容调用可执行文件并将结果存储在变量中,将为您提供与输出“行”对应的字符串数组中的标准输出

通常,如果要将字符串数组的元素组合成单个字符串,请使用
-join
。如

'one','two','three' -join 'xyz'
'one','two','three' -join "`r`n"
所以你可以

$result = nslookup <servername>
$singleString = $result -join "`r`n"
<process $singleString here>
$result=nslookup
$singleString=$result-join“`r`n”
或者,如果您在输出中搜索特定的字符串模式,我喜欢使用此模式,它分别处理每行输出:

nslookup <server> |?{ $_ -match 'someregex' } |%{ <use $matches here to process> }
nslookup |?{$|-match'someregex'}|%{}

除了使用
-join
获取字符串数组并创建单个字符串外,您还可以通过管道将nslookup的输出传输到
Out string
,例如:

$result = nslookup $server_name | Out-String