There are some situations when we would be using some common parameters throughout a script.
So Lets take an example of sending mail using send mail, now there would be a set of parameters which would be common like my SMTPServer, Port, From, UserSSL and Credentials.
Let me send email from my windows live account to my gmail account
So if i would like to do it the traditional way i could do something like
Send-MailMessage -From "vinithmenon28@live.com"` -SmtpServer "smtp.live.com" ` -UseSsl $true` -Port 587 ` -Credential (Get-Credential vinithmenon28@live.com) ` -To "vinithmenon28@gmail.com" ` -Subject "Hello From Gmail"
Now if we are using this Cmdlet again and again in a script, i can avoid all this copy paste by using $PSDefaultParameterValues.
With $PSDefaultParameterValues we can specify a HashTable for all these default values using a set of key-value pairs, Keys are the command names and the parameter names and the values consists of the value which needs to be bound to that parameter.
$PSDefaultParameterValues =@{ "Send-MailMessage:From" = "vinithmenon28@live.com"; "Send-MailMessage:SmtpServer" = "smtp.live.com"; "Send-MailMessage:UseSsl" = $true ; "Send-MailMessage:Port" = 587; "Send-MailMessage:Credential" = (Get-Credential vinithmenon28@live.com); }
So now anytime in my script execution powershell encounters send-mailmessage it binds the values already present in the hash table
So now if i do a send email its gonna grab the values from the hash table
Send-MailMessage -To vinithmenon28@gmail.com -Subject "Email with Less Typing :)"
I can also use wild cards and specify “*-MailMessage:From”, also maybe a “*From” so that any cmdlet which has any of these parameter’s would use the parameters bound in $PSDefaultParameterValues
so it would look something like below
$PSDefaultParameterValues =@{ "*:From" = "vinithmenon28@live.com"; "*:SmtpServer" = "smtp.live.com"; "*:UseSsl" = $true ; "*:Port" = 587; "*:Credential" = (Get-Credential vinithmenon28@live.com); }
Send-MailMessage -To vinithmenon28@gmail.com -Subject "Email with Less Typing :)"
And now if i again rerun send email i do see that it picks up the default parameter values.
PSDefaultParamaterValues can be disabled by just a one command as below.
$PSDefaultParameterValues["Disabled"] = $true