PowerTip: Predefine Cmdlet Parameters in Variable

PowerTip: Predefine Cmdlet Parameters in Variable

  • Comments 5
  • Likes

Summary: Pass a cluster of parameter values by using an array.

Hey, Scripting Guy! Question Is there an easy way to write Windows PowerShell commands to handle two separate domains
          (for example, production and development) and their credentials?

Hey, Scripting Guy! Answer Define them in an array that contains the parameter names and their values. For example, to pass
          the IP address of a domain controller and credentials as a single variable to the Get-ADUser cmdlet:

$DC=”192.168.1.5”

$Cred=(GET-CREDENTIAL)

$CommonParameters=@{‘Server’=$DC;’Credential’=$Cred)

GET-ADUSER –filter * @CommonParameters

Note If you ask a Windows PowerShell person, the popular term for this is “splatting.”

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Array =@() Hash = @{} PS >(@{}).GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Hashtable System.Object

  • FYI: The line below should have a closing curly bracket, not a closing parenthesis. $CommonParameters=@{‘Server’=$DC;’Credential’=$Cred)

  • This is interesting. I've never tried this method of using @CommonParameters before. I'm assuming in a real script you would have to get the variables for each environment at some point and assign them to $DC and $Cred. In your example you've hardcoded $DC and you're asking the user directly for $Cred. Are there differences to this method than passing the variables directly to the cmdlet? e.g. Get-ADUser -Server $DC -Credential $Cred