PowerShell 笔记 - 管道进阶

powershell 使用两种方式将一个命令的输出结果传入管道后的cmdlet,ByValueByPropertyName, 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 表达的意思相同

posted @ 2022-05-23 10:52  Chinor  阅读(163)  评论(0编辑  收藏  举报