I want to start a script1.ps1 out of an other script with arguments stored in a variable.
$para = "-Name name -GUI -desc ""this is the description"" -dryrun"
. .\script1.ps1 $para
The args I get in script1.ps1 looks like:
args[0]: -Name name -GUI -desc "this is the description" -dryrun
so this is not what I wanted to get.
Has anyone a idea how to solve this problem?
thx lepi
PS: It is not sure how many arguments the variable will contain and how they are going to be ranked.
Passing arguments in PowerShell is the same as in any other shell: you just type the command name, and then each argument, separated by spaces. If you need to specify the parameter name, you prefix it with a dash like -Name and then after a space (or a colon), the value.
Parameters can be created for scripts and functions and are always enclosed in a param block defined with the param keyword, followed by opening and closing parentheses. param() Inside of that param block contains one or more parameters defined by -- at their most basic -- a single variable as shown below.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
Working with variablesTo create a new variable, use an assignment statement to assign a value to the variable. You don't have to declare the variable before using it. The default value of all variables is $null . To get a list of all the variables in your PowerShell session, type Get-Variable .
You need to use splatting operator. Look at powershell team blog or here at stackoverflow.com.
Here is an example:
@'
param(
[string]$Name,
[string]$Street,
[string]$FavouriteColor
)
write-host name $name
write-host Street $Street
write-host FavouriteColor $FavouriteColor
'@ | Set-Content splatting.ps1
# you may pass an array (parameters are bound by position)
$x = 'my name','Corner'
.\splatting.ps1 @x
# or hashtable, basically the same as .\splatting -favouritecolor blue -name 'my name'
$x = @{FavouriteColor='blue'
Name='my name'
}
.\splatting.ps1 @x
In your case you need to call it like this:
$para = @{Name='name'; GUI=$true; desc='this is the description'; dryrun=$true}
. .\script1.ps1 @para
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With