简体   繁体   中英

Wrapper function with same name as command in Powershell?

I am making attempting to fix an app which has recently broken the ls command, using a Powershell wrapper script. My wrapper must have the same name as the command it is invoking, so I'm using invoke-command to call the original command.

# yarn broke 'ls'
function yarn() {
    $modifiedArgs = @()
    foreach ( $arg in $args ) {
        if ( $arg -cmatch '^ls$' ) {
            $arg = 'list'
        }
        $modifiedArgs = $modifiedArgs + $arg
    }
    invoke-command yarn -ArgumentList @modifiedArgs
}

However invoke-command fails with

Invoke-Command : Parameter set cannot be resolved using the specified named parameters

How can I run the original command with the modified parameters?

Edit: I've also tried -ArgumentList (,$modifiedArgs) per Passing array to another script with Invoke-Command and I still get the same error.

Edit: Looks like invoke-command is remoting only. I've also tried Invoke-Expression "& yarn $modifiedArgs" but that runs the function itself.

Per the powershell docs the & operator works:

# yarn broke 'ls'
function yarn() {
    $modifiedArgs = @()
    foreach ( $arg in $args ) {
        if ( $arg -cmatch '^ls$' ) {
            $arg = 'list'
        }
        $modifiedArgs += $arg
    }
    & 'C:\Program Files (x86)\Yarn\bin\yarn.cmd' $modifiedArgs
}

Still happy to accept other answers that don't involve specifying the command path explicitly.

I belive you can get around needing to specify the full path to the command if you scope the wrapper function to Private:

# yarn broke 'ls'
function Private:yarn() {
    $modifiedArgs = @()
    foreach ( $arg in $args ) {
        if ( $arg -cmatch '^ls$' ) {
            $arg = 'list'
        }
        $modifiedArgs += $arg
    }
    & yarn $modifiedArgs
}

This will prevent the function from being visible to child scopes, and it will revert back to using the application.

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