Expand string without Invoke-Expression

前端 未结 3 1264
忘了有多久
忘了有多久 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:45

    Embedding variables into strings is not the only way to create dynamic text, the way I would do it is like this:

    $WelcomeMessage = 'Hello {0}, today is {1}'
    
    # 100 lines of other functions and what not...
    
    function Greet-User
    {
        $Username = Get-UserNameFromSomewhereFancy
        $Date = Get-DateFromSomewhereFancy
    
        $WelcomeMessage -f $Username, $Date
    }
    

提交回复
热议问题