Search code examples
powershellaliasdotfiles

What is a proper way to pass a parameter to Set-Alias in powershell?


A little background:

I use PowerShell on windows xp at work and I set a bunch of useful shortcuts in Microsoft.PowerShell_profile.ps1 in My Documents, trying to emulate Mac environment inspired by Ryan Bates's shortcuts

I have things like:

Set-Alias rsc Rails-Console
function Rails-Console {Invoke-Expression "ruby script/console"}

Which works just fine when in command prompt I say:

rsc #it calls the proper command

However this doesn't work properly

Set-Alias rsg Rails-Generate
function Rails-Generate {Invoke-Expression "ruby script/generate"}

So when I do :

rsg model User

which is supposed to call

ruby script/generate model User

all it calls is

ruby script/generate  #Dumping  my params

So how would I properly modify my functions to take params I send to functions?

Thank you!!


Solution

  • Your function doesn't take any arguments so it's not terribly surprising that none get passed.

    You should write it like so:

    function Rails-Generate { ruby script/generate $args }
    

    Note that Invoke-Expression is unnecessary here. PowerShell is a shell—it has no problem calling other programs directly.

    Demo:

    PS Home:\> Set-Alias foo Call-Foo
    PS Home:\> function Call-Foo { args }
    PS Home:\> foo bar baz
    argv[0] = Somewhere\args.exe
    
    PS Home:\> function Call-Foo { args $args }
    PS Home:\> foo bar baz
    argv[0] = Somewhere\args.exe
    argv[1] = bar
    argv[2] = baz