简体   繁体   中英

Powershell equivalent of "$@" from bash

I don't know much about powershell, but I would like to run another script from powershell, and also pass along all the unused arguments. In bash I am doing it this way (simplified):

MY_PARAM=$1
shift
python otherscript.py "$@"

I have tried many things in powershell but nothing worked. In my python script I either received " System.Object[] " (or " System.Collections.Generic.List`1[System.Object] ") or all the arguments wrapped in a single string as the first argument (or various error messages of course). I have tried:

  • python otherscript.py $args
  • Invoke-Expression "python otherscript.py $args"
  • And in place of $args I have also tried using $MyInvocation.Line or $MyInvocation.UnboundArguments

What is the proper syntax for this?

Update 1

As Mathias R. Jessen comments, invoking the python script from the "global scope" with python otherscript.py $args works as I would expect.

What I am actually trying to do, is call my python script from within a function:

param (
    [string]$command = ""
)

function Invoke-Other() {
    python otherscript.py $args
}

switch ($command) {
    "foo" {
        Invoke-Other $args
    }
}

This is the setup, when I get a single, "wrapped" argument "bar baz", when I call my powershell script with .\\myscript.ps1 foo bar baz .

When you call Invoke-Other $args the argument list is passed as a single (array) argument, so all script arguments end up as a nested array in $args[0] inside the function. You can verify that by checking the value of $args.Count inside and outside the function. The nested array then gets mangled into a string when you call the Python script with the argument list of the function.

Use splatting to have the argument list of the script passed as individual arguments to the function:

Invoke-Other @args

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