Suppose I have a Powershell script similar to this:
$par = [...]
New-Connection `
-Server $par.Server `
-User $par.User `
-Pwd $par.Pwd `
- [...]
If $par.Pwd
is empty or null, New-Connection
will throw an error.
So, I only want to include this parameter, if $par.Pwd
has a value. Since there are a lot(!) of parameters, which might be empty, I don't want to write the command in 1000 different variations. I thought of sth like.
New-Connection `
-Server $par.Server `
-User $par.User `
$(if ($par.Pwd) {-Pwd $par.Pwd})
but this doesn't work.
How do I pass parameters to PowerShell scripts? 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.
To pass multiple parameters you must use the command line syntax that includes the names of the parameters. For example, here is a sample PowerShell script that runs the Get-Service function with two parameters. The parameters are the name of the service(s) and the name of the Computer.
The Force parameter has a different purpose. With the Force parameter, New-Item will overwrite any existing file with the same path. When used with Remove-Item , the Force parameter allows removal of files with Hidden or System attributes.
How about using the hashtable approach to creating new objects:
$Object = New-Object PSObject -Property @{
Name = $obj.Name
OptValue1 = $obj.OptValue1
OptValue2 = $obj.OptValue2
OptValue3 = $null
OptValue4 = "MyValue"
}
$Object
Update Splatting may also help, see here for more details, but if all your parameter names match you might be able to call New-Connection then pass it a hashtable containing your values.
New-Connection @par
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