Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - Conditionally add parameter/argument to cmdlet

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.

like image 227
marsze Avatar asked Sep 30 '13 11:09

marsze


People also ask

How do I add parameters to a PowerShell script?

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.

How do I pass multiple parameters to a PowerShell script?

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.

How do you force a parameter in PowerShell?

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.


1 Answers

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
like image 144
David Martin Avatar answered Nov 08 '22 13:11

David Martin