Caleb Jares
Caleb Jares

Reputation: 6307

First parameter in PowerShell function loses its value?

Here's a function that I call with .\GetEMSInstallers. For some unknown reason the first parameter always loses its value:

function Get-EMSInstallers {

param (
    $ems_for_amx_source = '\\server\ems_path',
    $installers_dir = 'D:\installers'
)

process {

    if (!(Test-Path "$installers_dir\EMS4AMX")) {
        "Copying files and folders from $ems_for_amx_source to $installers_dir\EMS4AMX"
        copy $ems_for_amx_source "$installers_dir\EMS4AMX" -rec -force
    }
}

}
Get-EMSInstallers $args

When I call it I get this output:

Copying files and folders from  to D:\installers\EMS4AMX
Copy-Item : Cannot bind argument to parameter 'Path' because it is an empty array.
At C:\Users\ad_ctjares\Desktop\Scripts\Ems\GetEMSInstallers.ps1:12 char:17
+             copy <<<<  $ems_for_amx_source "$installers_dir\EMS4AMX" -rec -force
    + CategoryInfo          : InvalidData: (:) [Copy-Item], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyArrayNotAllowed,Microsoft.PowerShell.Commands.CopyI
   temCommand

Upvotes: 0

Views: 648

Answers (1)

azhrei
azhrei

Reputation: 2323

When you don't pass in any argument to Get-EMSInstallers you still have a $args array - it is just empty. So the $ems_for_amx_source parameters is set to this empty array.

In other words, one way around this:

if ($args)
{
  Get-EMSInstallers $args
}
else
{
  Get-EMSInstallers
}

There is probably a more powershelly way to do this - I might revise this later if it comes to mind. :-) But that will get you started anyway.

Upvotes: 1

Related Questions