Peter Poulsen
Peter Poulsen

Reputation: 542

Matching properties of commands

I'm trying to hone my PowerShell skills, and as an exercise I'm trying to get all aliases pointing to Get-Content

(note: I'm fully aware that the easy way to do this is simply Get-Alias -Definition Get-Content, but I'm trying to do this using pipeing)

My attempt is to run something like:

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

or

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

but that returns blank.

Running Get-Alias | Get-Member reveals that the ReferencedCommand is a System.Management.Automation.CommandInfo which could explain why my attempts does not return anything.

Now I don't know where to go from here.

Anyone?

Upvotes: 0

Views: 81

Answers (2)

js2010
js2010

Reputation: 27516

Or you can use the -definition parameter. I've done this a lot. You can use wildcards and arrays.

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

Upvotes: 0

7cc
7cc

Reputation: 1179

First, please read Why is $false -eq "" true?

The same applies to Where-Object ... -eq

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

As you've already noticed, the type of the left-hand object is [CommandInfo] while the right type is [String].

Now, there are several way to make your code work.

# 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

Upvotes: 1

Related Questions