Author Posts

January 1, 2012 at 12:00 am

by mikekmcguire at 2013-01-24 16:21:56

Hello,

I'm unable to pass command-line values to a dot-sourced param block.

Using PowerShell v2, I have a series of scripts that require an extensive number of command-line parameters. To keep future maintenance down, I thought I'd be tricky and set these up as a separate .ps1 file, then dot-source this in at the start of each script.

I think I was too tricky for my own good. My naive assumption was that the contents of the dot-sourced file are essentially pasted in at the point of dot-sourcing, then the newly expanded source file re-parsed from the beginning, making the "Param(" of the dot-sourced file the "new" beginning of the file.

The parameters seem to be working. I have a mandatory one, and when I run the ps1 file that dot-sources the "parameter file", I get prompted to enter the missing parameter. The command-line values don't seem to be making it through, however.

I have tried passing in $args like this

. .\config_loader.ps1 $args
but get the following error:

C:\tfs\AlertSpace\dev\dec\Src\config_loader.ps1 : Cannot process argument transformation on parameter 'bcpPath'. Cannot convert value to type System.String.
At C:\tfs\AlertSpace\dev\dec\Src\mike1.ps1:1 char:2
+ . < <<< .\config_loader.ps1 $args
+ CategoryInfo : InvalidData: (:) [config_loader.ps1], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,config_load

"bcpPath" is the name of my first parameter, defined as

Param(

[parameter(Mandatory=$false)]
[alias("b")]
[string] $bcpPath = "bcp.exe",

Any idea if what I want to do is possible (perhaps in a different manner), or how I screwed up the process?

Thanks,
Mike

[edited for clarity]

by nohandle at 2013-01-25 05:21:00

Modules?

Topic: On my station the .sourced script accepts parameters normally:
dotsourced.ps1:
param ($dotSourced)
"`$dotSourced: $dotSourced"

Main:
. c:\temp\dotSourced.ps1

"`$args: $args"

.\main.ps1 'a'
$dotSourced:
$args: a

The error you get is because the content of $args cannot be converted to String.

by mikekmcguire at 2013-01-30 20:44:47

Thanks for the information — and sorry it took so long to reply.

I finally restructured the program. Now, I have an introductory script (load.ps1) that has the parameters set up in it. After they are all set, I dot-source the actual PowerShell file that does the work. The name of that file is passed in as a parameter to load.ps1. It's not an elegant solution, by any means, but it works!

Thanks again,
Mike