简体   繁体   中英

How can I set-alias for bunch of commands inside Foreach-Object?

I am trying to set-alias for all the existing powershell commands to exclude hyphen from the name. eg. Get-Alias would be aliased to GetAlias . I tired to achieve it by code below, however that doesn't seem to work. The function execution completes without any error, but when I check for new aliases using alias cmd, nothing has been created. When I just try the Set-Alias outside of the loop, that works but not inside. Any idea what could I be doing incorrectly in the code below? I also tried with Foreach-Object{//my code here} , that didn't work either.

I am using powershell ver 5.1

function _removeHyphenFromCommmands {
        $commands = Get-Command;
        foreach ($cmd in $commands) {
            $hyphenIndex = $cmd.Name.IndexOf("-");
            if ($hyphenIndex -gt -1) {
                $aliasName = $cmd.Name.Remove($hyphenIndex, 1);
                Set-Alias -Name $aliasName -Value $cmd -Description "hyphenless";
            }
        }
    }

When using set-alias , you are doing so within a scope. Since you are using it inside a function, theses aliases are valid only inside the function (where you instantly drop out of). You've got to set the scope via -scope parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM