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

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?

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

From my understanding of powershell, $args refers to the the arguments to the current function. The first time you call Write-Host, $args refers to the top-level arguments. Inside fun, you're referring to the arguments to fun, which are not given.

See PowerShell Variables for more information on variables.


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.


$MyInvocation.UnboundArguments

Need Your Help

A way to get unlock event in android?

android broadcastreceiver lockscreen

Is there a way to receive something like PHONE_UNLOCKED (with a BroadcastReceiver of some kind)?

Embedding Opera in Cocoa

cocoa embed opera

So, I'm writing a Cocoa application that needs to be able to display web content using Opera's rendering engine. This is for a feature, not because I'm an Opera fanboi (I'm not). All I've been able...