PowerShell String Formatting: Why is the colon character causing my variable's value to be blank?

前端 未结 2 699
野趣味
野趣味 2020-12-09 15:33

I was looking over what\'s coming with the next WinRM and PowerShell 3 and I was looking through the list of breaking changes and saw something that I\'d never seen before.<

2条回答
  •  萌比男神i
    2020-12-09 15:34

    The colon is a valid character for variable names, e.g. in $Env:PATH, etc.

    You can use the following option, too

    $server`: $status
    

    or, for some cases a format string is more readable:

    '{0}: {1}' -f $server, $status
    

    Back to the colon. There is a special case for variable names that correspond to an item on a PSDrive:

    $Env:Foo           # equivalent to the contents of Env:\Foo
    $Function:C:       # equivalent to the contents of Function:\C:
    ${C:\autoexec.bat} # ... you get the picture
    

    The syntax ${} exists to be able to specify variable names that otherwise use characters reserved for other parts of the syntax. You could see it as being similar (but more powerful) to C#'s @ in front of identifiers. See above where a \ is used in the variable name, since $Drive:Item only works for the current container on a drive (or the root for non-hierarchic ones like Env, Alias or Function).

    Another example where the variable name would be normally invalid syntax:

    PS> $+
    The term '$+' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
    spelling of the name, or if a path was included, verify that the path is correct and try again.
    At line:1 char:1
    + $+
    + ~~
        + CategoryInfo          : ObjectNotFound: ($+:String) [], CommandNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException
    
    PS> ${+} = 5
    PS> ${+}
    5
    PS> Get-Variable +
    
    Name                           Value
    ----                           -----
    +                              5
    

提交回复
热议问题