Powershell:使用带有字符串的 Select-Object 表达式 [英] Powershell : Use a Select-Object expression with a string
问题描述
对于某些脚本,我需要有一个由计算属性组成的输出.
For some scripts, i need to have an output composed of calculated properties.
例如,对于 ip.txt 中的 ip 地址列表,我想知道它们是否响应 ping.所以我尝试以下命令:
For example, for a list of ip addresses in ip.txt, i want to know if they respond to ping. So i try the following command:
Get-Content .\ip.txt | Select-Object $_,@{Name="ping?";Expression={Test-Connection $_ -Quiet -Count 1}}
但是我得到一个错误,不管我在脚本块表达式中做什么.
But i get an error, regardless of what i do in the scriptblock expression.
错误(法语,抱歉):
<代码>选择对象:参数空.请键入参加者doit être l'un des suivants:{System.String, System.Management.Automation.ScriptBlock}.Au niveau de ligne : 1 Caractère : 37+ 获取内容 .\ip.txt |选择对象<<<<<$_,@{Name="ping?";Expression={Test-Connection $_ -Quiet -Count 1}}+ CategoryInfo : InvalidArgument: (:) [Select-Object], NotSupportedException+ FullQualifiedErrorId : DictionaryKeyUnknownType,Microsoft.PowerShell.Commands.SelectObjectCommand
我之前在一些脚本中使用了计算属性",但使用了目录对象.为什么它不适用于字符串?
I used the "calculated properties" in some scripts before, but with directories objects. Why it doesnt work with strings?
推荐答案
试试这个,你需要为每个值创建计算属性:
try this instead, you need to create calculated properties for each value:
Get-Content .\ip.txt | Select-Object @{n="Server IP";e={$_}},@{n="ping?";e={[bool](Test-Connection $_ -Quiet -Count 1)}}
您代码中的问题是 $_
不是计算属性.Select-object
接受和属性数组,如果在您传递的数组中 $_
不被评估为属性.如果你只做 select-object $_
(如 select-object -prop $null )管道项目是输出.
The problem in your code is the $_
not the calculated property.
Select-object
accept and array of properties, if in the array you pass $_
isn't evaluated as a property.
If you do just select-object $_
(as select-object -prop $null ) piped items are the output.
这篇关于Powershell:使用带有字符串的 Select-Object 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!