Raj
Raj

Reputation: 1770

command line arguments from file

I have a powershell script for which I expect to pass quite few arguments in the command line. Having many arguments is not a problem since it is configured as a scheduled task but I'd like to make things easier for support people so that if ever they need to run the script from command line they have less things to type.

So, I am considering the option to have the arguments in a text file, either using Java-style properties file with key/value pairs in each line, or a simple XML file that would have one element per argument with a name element and a value element.

arg1=value1
arg2=value2

I'm interested with the views of PowerShell experts on the two options and also if this is the right thing to do.

Thanks

Upvotes: 1

Views: 382

Answers (2)

Keith Hill
Keith Hill

Reputation: 202092

If you want to use the ini file approach, you can easily parse the ini data like so:

$ini = ConvertFrom-StringData (Get-Content .\args.ini -raw)
$ini.arg1

The one downside to this approach is that all the arg types are string this works fine for strings and even numbers AFAICT. Where it falls down is with [switch] args. Passing True or $true doesn't have the desired effect.

Another approach is to put the args in a .ps1 file and execute it to get back a hashtable with all the args that you can then splat e.g:

-- args.ps1 --
@{
ComputerName = 'localhost'
Name = 'foo'
ThrottleLimit = 50
EnableNetworkAccess = $true
}

$cmdArgs = .\args.ps1
$s = New-PSSession @cmdArgs

Upvotes: 2

andyb
andyb

Reputation: 2772

To extend Keith's answer slightly, it's possible to set actual variables based on the values from the config file e.g.

$ini = ConvertFrom-StringData (Get-Content .\args.ini -raw)
$ini.keys | foreach-object { set-variable -name $_ -value $ini.Item($_) }

So a file containing

a=1
b=2
c=3

When processed with above code should lead to three variables being created:

$a = 1, $b = 2, $c = 3

I expect this would work for simple string values, but i'm fairly sure it would not be 'smart' enough to convert, say myArray = 1,2,3,4,5 into an actual array.

Upvotes: 0

Related Questions