Andrey Shchekin
Andrey Shchekin

Reputation: 21599

Powershell: Args/params not being populated

I have a PowerShell script:

param (
    [Parameter(Mandatory=$true)][string]$input,
    [Parameter(Mandatory=$true)][string]$table
)

Write-Host "Args:" $Args.Length
Get-Content $input |
    % { [Regex]::Replace($_, ",(?!NULL)([^,]*[^\d,]+[^,]*)", ",'`$1'") } |
    % { [Regex]::Replace($_, ".+", "INSERT INTO $table VALUES (`$1)") }

The Write-Host part is for debugging.
I run it as .\csvtosql.ps1 mycsv.csv dbo.MyTable (from powershell shell), and get

Args: 0
Get-Content : Cannot bind argument to parameter 'Path' because it is an empty s
tring.
At C:\temp\csvtosql.ps1:7 char:12
+ Get-Content <<<<  $input |
    + CategoryInfo          : InvalidData: (:) [Get-Content], ParameterBinding
   ValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAl
   lowed,Microsoft.PowerShell.Commands.GetContentCommand

I get exactly the same error with any parameters that I pass, also the same error if I try to use named parameters.

What can cause parameters not to be passed in?

UPDATE: PowerShell ISE asks me for these parameters using GUI prompts, then gives me the same error about them not being passed in.

Upvotes: 7

Views: 5109

Answers (3)

Aaron Jensen
Aaron Jensen

Reputation: 26749

You're calling your script with positional parameters (i.e. unnamed) and PowerShell doesn't know how to map them to your script parameters. You need to either call your script using the parameter names:

.\csvtosql.ps1 -input mycsv.csv -table dbo.MyTable

or update your script to specify your preferred order of positional parameters:

param (
    [Parameter(Mandatory=$true,Position=0)]
    [string]
    $input,

    [Parameter(Mandatory=$true,Position=1)]
    [string]
    $table
)

Upvotes: -1

Emiliano Poggi
Emiliano Poggi

Reputation: 24826

Upvotes: 4

Shay Levy
Shay Levy

Reputation: 126732

Unless you marked a parameter with the ValueFromRemainingArguments attribute (indicates whether the cmdlet parameter accepts all the remaining command-line arguments that are associated with this parameter), Args is "disabled". If all you need is the arguments count call the special variable:

$PSBoundParameters.Count

Upvotes: 5

Related Questions