命令的匹配属性

Matching properties of commands

我正在努力磨练我的 PowerShell 技能,作为练习,我正在尝试让所有别名都指向 Get-Content

(注意:我完全知道做到这一点的简单方法就是 Get-Alias -Definition Get-Content,但我正在尝试使用管道来做到这一点)

我的尝试是 运行 类似于:

Get-Alias | Where-Object -Property ReferencedCommand -eq Get-Content

Get-Alias | Where-Object -Property ReferencedCommand -eq "Get-Content"

但是那个 return 是空白的。

运行 Get-Alias | Get-Member 显示 ReferencedCommand 是一个 System.Management.Automation.CommandInfo 这可以解释为什么我的尝试没有 return 任何东西。

现在我不知道该何去何从。

有人吗?

首先请阅读Why is $false -eq "" true?

同样适用于Where-Object ... -eq

[pscustomobject]@{ val = 0 } | Where-Object val -eq "" # returns an object
[pscustomobject]@{ val = "" } | Where-Object val -eq 0 # null

正如您已经注意到的,左侧对象的类型是 [CommandInfo] 而正确的类型是 [String].

现在,有几种方法可以使您的代码正常工作。

# ReferencedCommand.Name = "Get-Content"
Get-Alias | Where-Object { $_.ReferencedCommand.Name -eq "Get-Content" }

# put [string] in the left
Get-Alias | Where-Object { "Get-Content" -eq $_.ReferencedCommand }

# `-Like` operator casts the left side as [string]
Get-Alias | Where-Object -Property ReferencedCommand -Like Get-Content

或者您可以使用-definition 参数。我已经做了很多。您可以使用通配符和数组。

get-alias -Definition get-content

alias -d get-content


CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           cat -> Get-Content
Alias           gc -> Get-Content
Alias           type -> Get-Content