Here is my code:
# hi.ps1
function fun
{
Write-Host $args
}
Write-Host '---------------'
Write-Host $args
Write-Host '---------------'
fun
Write-Host '---------------'
This is the output:
PS C:\scratch> .\hi there jim
---------------
there jim
---------------
---------------
My question is, why isn't $args visible within fun?
Think of a script file like a function. The function body is the script content and the function name is the script file name. When you send arguments to the script they will be avaiable in the script content. When you send arguments to a function $args will be accessible inside the function.
Take the following for example:
# .\test-args.ps1function foo{ write-host "printing function `$args $args"}
# print script argswrite-host "printing script `$args $args"
# print function argsfoo hello world ...
# end of scriptIt seems that $args has "script" scope. There are three scopes: local, global, and script.
If the function is changed like this:
function fun
{
Write-Host $script:args
}
Then it will work. The "script:" is a scope resolution operator ("local:" is the default). I found that result somewhat experimentally, and I can't say I know what the point of script scope is exactly, but it appears that variables in script scope belong to the script itself in some way.
Edit: I'm accepting my own answer as the best one since it is what solved my problem, but also see the other answers and their comments for some useful information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With