Casey Chester
Casey Chester

Reputation: 276

Why does PowerShell code behave different when called from a function?

Experienced C# developer learning PowerShell here so I am sure I am just missing something silly. What I am trying to do is write a function that simply writes it's input to a temporary file in JSON format. I have code that works fine if I run it 'inline', but that same code writes an empty file when called in a function.

Here is the code:

function Dump-File {
    param (
        [Parameter(Mandatory=$true)]
        $Input
    )
    $tmp = New-TemporaryFile
    $Input | ConvertTo-Json | Out-File $tmp.FullName 
    Write-Output "Dump file written: $($tmp.FullName)"
}

$args = @{}
$args.Add('a', 1)
$args.Add('b', 2)
$args.Add('c', 3)
$args.Add('d', 4)

# results in json written to temp file
$tmp = New-TemporaryFile
$args | ConvertTo-Json | Out-File $tmp.FullName
Write-Output "args dumped: $($tmp.FullName)"

# results in empty temp file
Dump-File $args

Can anyone help me understand why the code called inline works but the same code does not work when I wrap it up as a function?

Upvotes: 2

Views: 155

Answers (1)

Sage Pourpre
Sage Pourpre

Reputation: 10323

$Input is an automatic variable.

Changing the name of your Dump-File parameter to $somethingelse will resolve your problem. Never use $input as a parameter or variable name.

Automatic variables are to be considered read-only.

About Automatic Variables

SHORT DESCRIPTION

Describes variables that store state information for PowerShell. These variables are created and maintained by PowerShell.

LONG DESCRIPTION

Conceptually, these variables are considered to be read-only. Even though they can be written to, for backward compatibility they should not be written to.

Here is a list of the automatic variables in PowerShell:

...

$INPUT

Contains an enumerator that enumerates all input that is passed to a function. The $input variable is available only to functions and script blocks (which are unnamed functions). In the Process block of a function, the $input variable enumerates the object that is currently in the pipeline. When the Process block completes, there are no objects left in the pipeline, so the $input variable enumerates an empty collection. If the function does not have a Process block, then in the End block, the $input variable enumerates the collection of all input to the function.

Source: About_Automatic_Variables

This information is also avaible through Get-help command

Get-Help about_Automatic_Variables

Upvotes: 2

Related Questions