Reputation: 17154
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.
Upvotes: 14
Views: 9770
Reputation: 12248
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
Upvotes: 11