Chris Magnuson
Chris Magnuson

Reputation: 5949

Is there a way to set a default value for a named parameter across many function calls in PowerShell?

Is there a way to set a default value for a named parameter across many function calls in PowerShell?

For example if I have the following code:

$ComputerName = "ComputerName"
Invoke-Command -ComputerName $ComputerName -ScriptBlock {hostname}
Get-WmiObject -ComputerName $ComputerName -Class Win32_OperatingSystem
Get-Process -ComputerName $ComputerName
Get-Service -ComputerName $ComputerName

Instead of specifying -ComputerName for every command I want to set it once and have each command use the value I specified.

One way to do this would be splatting:

$ComputerNameParameter = @{ComputerName = $ComputerName }
Invoke-Command @ComputerNameParameter -ScriptBlock {hostname}
Get-WmiObject @ComputerNameParameter -Class Win32_OperatingSystem
Get-Process @ComputerNameParameter
Get-Service @ComputerNameParameter

This isn't much better than the original.

I really want to be able to set a default so that while my default value is set all functions I call that have a -ComputerName parameter will use my default value unless I specify otherwise.

The End result would look something like this:

Set-DefaultValueForFunctionNamedParameter -Name ComputerName -Value $ComputerName
Invoke-Command -ScriptBlock {hostname}
Get-WmiObject -Class Win32_OperatingSystem
Get-Process
Get-Service

Does something like this exist in PowerShell?

Upvotes: 2

Views: 714

Answers (2)

MisterSeajay
MisterSeajay

Reputation: 4659

Use $PSDefaultParameterValues (PowerShell 3.0 and later):

The $PSDefaultParameterValues preference variable lets you specify custom default values for any cmdlet or advanced function. Cmdlets and functions use the custom default value unless you specify another value in the command.

about_Parameters_Default_Values

Since the Hashtable $PSDefaultParameterValues exists by default, you don't need to set it explicity. That is, could can just add a new Key-Value pair, so both the following work:

$PSDefaultParameterValues = @{"*:ComputerName" = $ComputerName}

$PSDefaultParameterValues['*:ComputerName'] = $ComputerName

For those who don't want to read the document, the syntax of the keys in this hashtable is: <cmdlet>:<parameter>.

In the example here, cmdlet is set to '*' to set the default value for all cmdlets.

Upvotes: 2

Chris Magnuson
Chris Magnuson

Reputation: 5949

From the list of similar questions I saw people talking about using $PSDefaultParameterValues which is explained in about_Parameters_Default_Values.

Here is how it could be used to solve my example:

$PSDefaultParameterValues = @{"*:ComputerName" = $ComputerName}
Invoke-Command -ScriptBlock {hostname}
Get-WmiObject -Class Win32_OperatingSystem
Get-Process
Get-Service

Upvotes: 2

Related Questions