在PowerShell中获取Windows 32位格式的时间/日期



是否有PowerShell命令用于将当前datetime检索为以Windows C Runtime 32位时间/日期格式编码的值?

我不知道已经存在这样的函数。你可以手动这样做:

$date = Get-Date
[uint16]$encodedTime = (((($date.Hour) -shl 6) + $date.Minute) -shl 5) + $date.Second / 2
[uint16]$encodedDate = (((($date.Year - 1980) -shl 4) + $date.Month) -shl 5) + $date.Day

如果需要,您可以进一步组合这些值:

[uint32]$encodedTimeDate = $encodedTime -shl 16 + $encodedDate
[uint32]$encodedDateTime = $encodedDate -shl 16 + $encodedTime

为了补充stackprotector的出色回答,我使用他的代码创建了两个助手函数,以转换为dos日期时间值和从dos日期时间转换为值:

function ConvertTo-DosDateTime {
[CmdletBinding()]
param (
[Parameter(Mandatory = $false, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[DateTime]$Date = (Get-Date)
)
# seconds are stored divided by 2
[uint16]$encodedTime = (((($Date.Hour) -shl 6) + $Date.Minute) -shl 5) + ($Date.Second -shr 1)
[uint16]$encodedDate = (((($Date.Year - 1980) -shl 4) + $Date.Month) -shl 5) + $Date.Day
([uint32]$encodedDate -shl 16) + $encodedTime
}
function ConvertFrom-DosDateTime {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[uint32]$DosDate
)
# split the 4 bytes into a date and a time part
[uint32]$encodedDate = $DosDate -shr 16
[uint32]$encodedTime = $DosDate -band 0xffff
# shift and mask-off the relevant bits
$day   = $encodedDate -band 0x1f                    # 5 bits  (0-4)
$month = ($encodedDate -shr 5) -band 0xf            # 4 bits  (5-8)
$year  = (($encodedDate -shr 9) -band 0x7f) + 1980  # 7 bits  (9-15)
# same for the time part
$secs  = ($encodedTime -band 0x1f) * 2              # 5 bits  (0-4)
$mins  = ($encodedTime -shr 5) -band 0x3f           # 6 bits  (5-10)
$hrs   = ($encodedTime -shr 11) -band 0x1f          # 5 bits  (11-15)
# return as DateTime object
Get-Date -Year $year -Month $month -Day $day -Hour $hrs -Minute $mins -Second $secs -Millisecond 0
}

当然,所有学分都归stackprotector所有。

最新更新