我需要创建一些包含当前时间的日志
,我不想重复调用 Get-Date cmdlet
我怎样才能简单地设置一个动态变量?
我尝试过这个:
$CurrentTime=(Get-Date -Format "yyyy-MM-dd_HH:mm:ss:ffff"::Now)
<# Some code #>
Write-host $CurrentTime::Now "int result 1"
<# Some code #>
Write-host $CurrentTime::Now "int result 2"
<# Some code #>
Write-host $CurrentTime::Now "int result 3"
但输出的格式错误。
24.10.2022 18:53:35 int result 1
24.10.2022 18:53:35 int result 2
24.10.2022 18:53:35 int result 3
我该如何修复它?
答案1
我找到了如何使用函数来实现它的答案:
function CurrentTime
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string]$CurrentTime
)
Write-Output ("{0} - {1}" -f (Get-Date -Format "yyyy-MM-dd_HH:mm:ss:ffff"), $CurrentTime)
}
Write-host | CurrentTime "int result 1"
<# Some code #>
Write-host | CurrentTime "int result 2"
<# Some code #>
Write-host | CurrentTime "int result 3"
结果输出:
2022-10-24_22:15:21:4042 - int result 1
2022-10-24_22:15:21:4052 - int result 2
2022-10-24_22:15:21:4062 - int result 3
答案2
创建动态变量
$Global:CurrentTime = Set-PSBreakpoint -Variable CurrentTime -Mode Read -Action { Set-Variable CurrentTime (Get-Date -Format "yyyy-MM-dd_HH:mm:ss:ffff") -Option ReadOnly, AllScope -Scope Global -Force }
Write-host $CurrentTime "int result 1"
结果
2022-10-26_00:17:09:8975 int result 1