Expand string without Invoke-Expression

前端 未结 3 1354
忘了有多久
忘了有多久 2021-01-14 00:20

Imagine the following code:

# Script Start
$WelcomeMessage = \"Hello $UserName, today is $($Date.DayOfWeek)\"

..
..
# 100 lines of other functions and what          


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-14 00:44

    The canonical way to delay evaluation of expressions/variables in strings is to define them as single-quoted strings and use $ExecutionContext.InvokeCommand.ExpandString() later on.

    Demonstration:

    PS C:\> $s = '$env:COMPUTERNAME'
    PS C:\> $s
    $env:COMPUTERNAME
    PS C:\> $ExecutionContext.InvokeCommand.ExpandString($s)
    FOO

    Applied to your sample code:

    $WelcomeMessage = 'Hello $UserName, today is $($Date.DayOfWeek)'
    
    ...
    ...
    ...
    
    function Greet-User {
      $Username = Get-UserNameFromSomewhereFancy
      $Date = Get-DateFromSomewhereFancy
    
      $ExecutionContext.InvokeCommand.ExpandString($WelcomeMessage)
    }
    

提交回复
热议问题