Search code examples
powershellprofilestring-literalsstring-interpolationdefault-parameters

Powershell Script wont add $PSDefaultParameterValues to $profile


I'm writing a quick Powershell script to import modules and update some default parameters on various machines. I'm running into an issue where in my script when I add $PSDefaultParameterValues to the $profile it changes to System.Management.Automation.DefaultParameterDictionary which then throws an error of not being recognized as the name of a cmdlet.

Here is the code in my ps1 script

Add-Content -Path $PROFILE -Value "$PSDefaultParameterValues = @{}"

Here is what gets added to the profile

System.Management.Automation.DefaultParameterDictionary = @{}

I've tried everything from using Set-Content to using variables to avoid quotation confusion.

I appreciate the help!


Solution

  • To add to tonypags' helpful answer:

    • Double-quoted PowerShell strings ("...") are expandable strings, i.e they perform string interpolation of embedded variable references (e.g. $PSDefaultParameterValues) and subexpressions (e.g. $(1 + 2))

    • Single-quoted strings ('...') are verbatim strings, i.e. their content is used as-is (verbatim, literally).


    Thus, the automatic $PSDefaultParameterValues variable was expanded in your "..." string, which in essence means it was replaced with its .ToString() representation - which in this case is simply the type name of the variable's value.

    • If your entire string is meant to be used verbatim, use '...' quoting, as shown in tonypags' answer.

    • If you do need expansions (string interpolation), but need to selectively suppress them, escape $ characters as `$, using ` (a backtick), PowerShell's escape character, as shown in the following example:

       $enc = 'utf8'
       # Note the backtick (`) before $PSDefaultParameterValues.
       # NOTE: It is only the *outer* quoting that determines 
       #       whether expansion is performed.
       Add-Content -Path $PROFILE `
                   -Value "`$PSDefaultParameterValues = @{ '*:Encoding' = '$enc' }"