PowerShell 笔记 - 管道进阶
powershell 使用两种方式将一个命令的输出结果传入管道后的cmdlet,ByValue
和 ByPropertyName
, ByValue
方式的优先级更高一点
ByValue进行管道输入
当使用ByValue这种方式实现管道参数绑定时,PowerShell会确认命令A产生的数据对象类型,然后查看命令B中哪个参数可以接受经由管道传来对象的类型。
例如Get-Service
接受管道输入, 可以使用以下方式查看参数接受管道输入的细节。
Get-Help Get-Service -full
...
-ComputerName <System.String[]>
Gets the services running on the specified computers. The default is the local computer.
Type the NetBIOS name, an IP address, or a fully qualified domain name (FQDN) of a remote computer. To specify
the local computer, type the computer name, a dot (`.`), or localhost.
This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of `Get-Ser
vice` even if your computer is not configured to run remote commands.
是否必需? False
位置? named
默认值 None
是否接受管道输入? True (ByPropertyName)
是否接受通配符? False
...
-Name <System.String[]>
Specifies the service names of services to be retrieved. Wildcards are permitted. By default, this cmdlet gets
all of the services on the computer.
是否必需? False
位置? 0
默认值 None
是否接受管道输入? True (ByPropertyName, ByValue)
是否接受通配符? True
...
ByPropertyName接受管道输入
ByPropertyName 与ByValue稍有不同。通过该方法,命令B的多个参数可以被同时使用。原理就是powershell寻找能够匹配参数名称的属性名称。
例子
ByValue
举例
> Get-Content .\host.txt
ComputerName
.
Javis
> Import-Csv .\host.txt | Select-Object -ExpandProperty computername
.
Javis
# ExpandProperty 是为了把查询到的计算机名称转为string类型
> Get-Process -ComputerName (Import-Csv .\host.txt | Select-Object -ExpandProperty computername)
# 最后即可查询host.txt 文件中计算机的进程
ByPropertyName
举例
> Get-Content .\user.txt
login,dept,city,title
Donj,IT,Las Vegas,CTO
GregS,IT,New York,CEO
Bruu,Business,Ciie,CFO
Import-CSV .\user.txt | Select-Object -Property *, @{name='samAccountName';expression={$_.login}},@{label='name';expression={$_.login}},@{n='department';e=${$_.dept}} | New-ADUser
# 此处@{name='xxx',e='xxx'}用于构建hashtable, 构建新的对象的属性。 name,n,label,l 表达的意思相同
分类:
PowerShell
, Windows
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构