I have a script tester.ps1; the first thing it does is call a function (defined within the script itself) called main.
I need to pass in the automatic variable $args that was passed into it from the commandline.
How do I do this?
The following doesn't seem to work:
#Requires -Version 5.0
#scriptname: tester.ps1
function main($args) {
Write-Host $args
}
# Entry point
main $args
When I save this tester.ps1 and call it, the function doesn't see the passed-in parameter?
PS> . .\tester.ps1 hello world From entry point: hello world From Function:
$argsas a param in your function:function main {write-host $args }$argsas an actual parameter; it's already a special value that always contains all the arguments to a function. In this case, simply making itmain()is sufficient. (Passing$argsto it is still required.) Saving$argsoutside the function in a global variable is another option, if you had many functions that needed access to all of them.