在字符串中编写powershell函数

Don*_*nio 2 powershell

如果我有:

Write-Host "[$(Get-Date -displayhint time)] backup starting..."
Run Code Online (Sandbox Code Playgroud)

我明白了:

[02/17/2010 1:26:12 pm]备份开始......

一世.即 该Get-Date参数被忽略,只是返回的输出Get-Date.

在字符串中间注入当前时间的最佳方法是什么?

谢谢

Joe*_*oey 8

好吧,在这种情况下,您将转换为字符串,因为您正在使用字符串中的输出.Get-Date命令的结果仍然是DateTime对象.然后,Out-Host cmdlet将显示提示.

您可以使用该-Format参数强制使用某种格式,在这种情况下,cmdlet会返回一个字符串:

Get-Date -Format T
Run Code Online (Sandbox Code Playgroud)

("T"作为全时的格式字符串),然后看起来像这样:

PS Home:\> Write-Host "[$(Get-Date -Format T)] backup starting..."
[19:35:12] backup starting...
Run Code Online (Sandbox Code Playgroud)