绑定到参数

时间:2019-08-12 07:10:50

标签: powershell

我试图了解PowerShell中的参数绑定,特别是为什么这样的命令

Get-ChildItem users.csv | Get-Acl

有效。

Get-Acl通过管道接受2个参数:

  • -Path
    • 类型为String []
    • 接受ByValue和ByPropertyName参数
  • -LiteralPath
    • 类型为String []
    • 接受ByValue和ByPropertyName参数

的输出
Get-ChildItem users.csv

System.IO.FileInfo对象,PowerShell不能将其绑定到Get-Acl的参数。

这是因为:

  1. 按值绑定失败,因为PowerShell不会将FileInfo对象转换为字符串。
  2. 由于属性名称的绑定也将失败,因为FileInfo对象没有任何PathLiteralPath属性。

运行跟踪表明LiteralPath的{​​{1}}参数已成功与PropertyName绑定:

Get-Acl

输出如下(摘录所示):

ParameterBinding Information: 0 :     Parameter [LiteralPath] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION
ParameterBinding Information: 0 :     BIND arg [Microsoft.PowerShell.Core\FileSystem::C:\Users\xxx\users.csv] to parameter [LiteralPath]
ParameterBinding Information: 0 :         Binding collection parameter LiteralPath: argument type [String], parameter type [System.String[]], collection type Array, element type [System.String], no coerceElementType
ParameterBinding Information: 0 :         Creating array with element type [System.String] and 1 elements
ParameterBinding Information: 0 :         Argument type String is not IList, treating this as scalar
ParameterBinding Information: 0 :         Adding scalar element of type String to array position 0
ParameterBinding Information: 0 :         Executing VALIDATION metadata: [System.Management.Automation.ValidateNotNullOrEmptyAttribute]
ParameterBinding Information: 0 :         BIND arg [System.String[]] to param [LiteralPath] SUCCESSFUL

PowerShell从何处获取FileInfo对象的Trace-Command -Expression { Get-ChildItem users.csv | Get-Acl } -Name ParameterBinding -PSHost 属性?

1 个答案:

答案 0 :(得分:3)

因为LiteralPath的别名为PSPath-FileInfo提供者返回的FileSystem对象都具有PSPath属性!

PSPathLiteralPath的别名:

PS C:\> (Get-Command Get-Acl).Parameters['LiteralPath'].Aliases
PSPath

FileInfo上的提供程序属性

PS C:\> Get-Item C:\Windows\System32\notepad.exe|Get-Member -MemberType NoteProperty

   TypeName: System.IO.FileInfo

Name          MemberType   Definition
----          ----------   ----------
PSChildName   NoteProperty string PSChildName=notepad.exe
PSDrive       NoteProperty PSDriveInfo PSDrive=C
PSIsContainer NoteProperty bool PSIsContainer=False
PSParentPath  NoteProperty string PSParentPath=Microsoft.PowerShell.Core\FileSystem::C:\Windows\System32
PSPath        NoteProperty string PSPath=Microsoft.PowerShell.Core\FileSystem::C:\Windows\System32\notepad.exe
PSProvider    NoteProperty ProviderInfo PSProvider=Microsoft.PowerShell.Core\FileSystem

如您所见,PSPath NoteProperty包含文件系统项的提供程序限定的文字路径,就像在获取Microsoft.PowerShell.Core\FileSystem::C:\Users\xxx\users.csv

的跟踪输出中一样