Powershell 时间跨度不一致

Powershell Timespan inconsistent

在我的 powershell 脚本的开头,我有以下内容,

$scriptStarted = Get-Date

在脚本的最后,我有

$scriptDuration = New-Timespan -Start $scriptStarted -End (Get-Date)
Write-Log -Message ("Script Complete. Script duration {0:hh} hours, {0:mm} minutes and {0:ss} seconds" -f $scriptDuration) -Path $logFile

我正在使用来自 here

的 Write-Log

在脚本中,一些部分包含在它们自己的持续时间查找器中。这是一个 SQL 查询示例

$queryStarted = Get-Date
Write-Log "Executing Query..." -Path $logFile
Invoke-SqlCmd -ServerInstance $dbConfig.Server -Database $dbConfig.Database -Credential $dbConfig.Credential -Query $dbConfig.Query -OutputSqlErrors $true | Out-File -FilePath $dbConfig.DataFile -Width 250
$queryDuration = New-Timespan -Start $transferStarted -End (Get-Date)
Write-Log -Message ("Query Complete.  Query duration {0:hh} hours, {0:mm} minutes and {0:ss} seconds" -f $queryDuration) -Path $logFile

我的问题是 $scriptDuration 小于 $queryDuration

查询持续时间 详细:查询完成。查询时长00小时19分10秒

脚本持续时间 详细:脚本完成。剧本时长00小时12分43秒

脚本持续时间应长于其中的任何部分。

我的意思是你弄错了变量,所以这个:

$queryStarted = Get-Date
# ...
$queryDuration = New-Timespan -Start $transferStarted -End (Get-Date)

应该是这样的:

$queryStarted = Get-Date
# ...
$queryDuration = New-Timespan -Start $queryStarted -End (Get-Date)

但一般人做这种事情的时候,都会用System.Diagnostics.Stopwatch

# Create new instance and start
$Stopwatch = [System.Diagnostics.Stopwatch]::StartNew()

# Your code here

#Stop the Stopwatch
$Stopwatch.Stop()
"Duration {0:hh} hours, {0:mm} minutes and {0:ss} seconds" -f $Stopwatch.Elapsed

生成的时间跨度对象位于 $Stopwatch.Elapsed。秒表可以停止、启动、重置等。它会为您处理所有数学运算,并知道已经过了多长时间 运行。