Why this PowerShell alias does not work?

2

0

I am learning PowerShell.

I would like to understand why some aliases in PowerShell 5.0 under Windows 8.1 do not work.

For instance, this command alone works:

Get-WmiObject -Class Win32_WinSAT

But it does not when defined in my $profile as follows:

Set-Alias -Name wei -Value 'Get-WmiObject -Class Win32_WinSAT'

The error message follows:

PS C:\> wei
wei : The term 'Get-WmiObject -Class Win32_WinSAT' is not recognized as the 
name of a cmdlet, function, script file,
or operable program. Check the spelling of the name, or if a path was 
included, verify that the path is correct and
try again.
At line:1 char:1
+ wei
+ ~~~
    + CategoryInfo          : ObjectNotFound: (Get-WmiObject -Class Win32_WinSAT:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

EDIT:

I see the aliases work a little different than in standard Bash on Linux I am used to.

The solution was to simply declare it as a function:

Function wei { Get-WmiObject -Class Win32_WinSAT }

LinuxSecurityFreak

Posted 2017-07-19T04:48:16.400

Reputation: 2 298

1Your alias equivalent to & 'Get-WmiObject -Class Win32_WinSAT'. – user364455 – 2017-07-19T05:01:06.453

Answers

1

Normally PowerShell tries to use the first space to separate the command from the parameters. However, you can use a string to specify that a space is just part of a file. This essentially lets you treat the space like a non-special character, and allows you to treat something like 'C:\Program Files\Windows NT\Accessories\notepad.exe' as if it was one word, not two.

That's essentially what you're doing. PowerShell cannot find a command named 'Get-WmiObject -Class Win32_WinSAT', because there is no such command. (The command in question is simply 'Get-WmiObject', not 'Get-WmiObject -Class Win32_WinSAT'.

TOOGAM

Posted 2017-07-19T04:48:16.400

Reputation: 12 651

So, I have now identified the problem. I realize I haven't provided a workaround/solution. Being that I am supposed to be at work in less than 5 hours and should get some more sleep before then, I will allow someone else that pleasure. Hopefully my comment helped identify the right track of what needed to be solved. – TOOGAM – 2017-07-19T10:10:58.127

1

If you like to pass other parameters to your alias, you can do this:

function wei([Parameter(ValueFromRemainingArguments = $true)]$params) {
    & Get-WmiObject -Class Win32_WinSAT $params
}

ahmadali shafiee

Posted 2017-07-19T04:48:16.400

Reputation: 223