Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I access $args from inside a function?

Tags:

powershell

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?

like image 390
dan-gph Avatar asked Feb 25 '26 08:02

dan-gph


2 Answers

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.ps1

function foo{ write-host "printing function `$args $args"}

# print script args

write-host "printing script `$args $args"

# print function args

foo hello world ...

# end of script
like image 92
Shay Levy Avatar answered Feb 27 '26 02:02

Shay Levy


It 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.

like image 26
dan-gph Avatar answered Feb 27 '26 01:02

dan-gph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!