dan-gph
dan-gph

Reputation: 16899

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?

Upvotes: 3

Views: 1266

Answers (4)

Antony Denyer
Antony Denyer

Reputation: 1611

$MyInvocation.UnboundArguments

Upvotes: 0

dan-gph
dan-gph

Reputation: 16899

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.

Upvotes: 4

Shay Levy
Shay Levy

Reputation: 126712

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

Upvotes: 4

Kevin Lacquement
Kevin Lacquement

Reputation: 5117

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.

Upvotes: 2

Related Questions