How can you use an object's property in a double-quoted string?

前端 未结 4 2052
耶瑟儿~
耶瑟儿~ 2020-11-21 07:18

I have the following code:

$DatabaseSettings = @();
$NewDatabaseSetting = \"\" | select DatabaseName, DataFile, LogFile, LiveBackupPath;
$NewDatabaseSetting.         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 07:57

    Documentation note: Get-Help about_Quoting_Rules covers string interpolation, but, as of PSv5, not in-depth.

    To complement Joey's helpful answer with a pragmatic summary of PowerShell's string expansion (string interpolation in double-quoted strings ("...", a.k.a. expandable strings), including in double-quoted here-strings):

    • Only references such as $foo, $global:foo (or $script:foo, ...) and $env:PATH (environment variables) are recognized when directly embedded in a "..." string - that is, only the variable reference itself is expanded, irrespective of what follows.

      • To disambiguate a variable name from subsequent characters in the string, enclose it in { and }; e.g., ${foo}.
        This is especially important if the variable name is followed by a :, as PowerShell would otherwise consider everything between the $ and the : a scope specifier, typically causing the interpolation to fail; e.g., "$HOME: where the heart is." breaks, but "${HOME}: where the heart is." works as intended.
        (Alternatively, `-escape the :: "$HOME`: where the heart is.").

      • To treat a $ or a " as a literal, prefix it with escape char. ` (a backtick); e.g.:
        "`$HOME's value: `"$HOME`""

    • For anything else, including using array subscripts and accessing an object variable's properties, you must enclose the expression in $(...), the subexpression operator (e.g., "PS version: $($PSVersionTable.PSVersion)" or "1st el.: $($someArray[0])")

      • Using $(...) even allows you to embed the output from entire command lines in double-quoted strings (e.g., "Today is $((Get-Date).ToString('d')).").
    • Interpolation results don't necessarily look the same as the default output format (what you'd see if you printed the variable / subexpression directly to the console, for instance, which involves the default formatter; see Get-Help about_format.ps1xml):

      • Collections, including arrays, are converted to strings by placing a single space between the string representations of the elements (by default; a different separator can be specified by setting $OFS) E.g., "array: $(@(1, 2, 3))" yields array: 1 2 3

      • Instances of any other type (including elements of collections that aren't themselves collections) are stringified by either calling the IFormattable.ToString() method with the invariant culture, if the instance's type supports the IFormattable interface[1], or by calling .psobject.ToString(), which in most cases simply invokes the underlying .NET type's .ToString() method[2], which may or may not give a meaningful representation: unless a (non-primitive) type has specifically overridden the .ToString() method, all you'll get is the full type name (e.g., "hashtable: $(@{ key = 'value' })" yields hashtable: System.Collections.Hashtable).

      • To get the same output as in the console, use a subexpression and pipe to Out-String and apply .Trim() to remove any leading and trailing empty lines, if desired; e.g.,
        "hashtable:`n$((@{ key = 'value' } | Out-String).Trim())" yields:

            hashtable:                                                                                                                                                                          
            Name                           Value                                                                                                                                               
            ----                           -----                                                                                                                                               
            key                            value      
        

    [1] This perhaps surprising behavior means that, for types that support culture-sensitive representations, $obj.ToString() yields a current-culture-appropriate representation, whereas "$obj" (string interpolation) always results in a culture-invariant representation - see this answer.

    [2] Notable overrides:

    • The previously discussed stringification of collections (space-separated list of elements rather than something like System.Object[]).
    • The hashtable-like representation of [pscustomobject] instances (explained here) rather than the empty string.

提交回复
热议问题