powershell - 如何使用 PowerShell 将 UTC 转换为 EST

标签 powershell csv powershell-2.0

在我的 csv 文件中,我有日期和时间列,但它是 UTC 时间,所以我只是想知道如何使用 PowerShell 将其转换为 EST 时间(12 小时或 24 小时格式)。我一直在 Google 上搜索如何执行此操作,但尚未看到 Excel 列的任何解决方案。


function Convert-JSONColumn {

    Write-Host "Start parsing Json Column"

    $downloadFile = Import-Csv "C:\AuditLogSearch\Downloaded-Audit-Log-Records.csv"
    $modifiedFile = "C:\AuditLogSearch\Modified-Audit-Log-Records.csv"
 
    $downloadFile | ForEach-Object {
        $jSON = $_.AuditData | ConvertFrom-Json
        $epdata = ""
        foreach ($ep in $jSON.extendedProperties) {
            $epdata += $ep.Name + " : " + $ep.Value + "`n"
        }
        $paramdata = ""
        foreach ($param in $jSON.Parameters) {
            $paramdata += $param.Name + " : " + $param.Value + "`n"
        }

        New-Object PsObject -Property @{
            RecordType            = $_.RecordType
            UserIds               = $_.UserIds
            Operations            = $_.Operations
            CreationTime          = $jSON.CreationTime
            Operation             = $jSON.Operation
            ObjectId              = $jSON.ObjectId
        }

    } | Select-object -Property @(
        @{Name = 'User'; Expression = 'UserId' }
        @{Name = 'Date & Time'; Expression = 'CreationTime' }
        @{Name = 'Type of Action'; Expression = 'Operation' }
        @{Name = "Criteria"; Expression = "RecordType" }
        @{Name = "Item Search"; Expression = "ObjectId" }
        @{Name = "Result Status"; Expression = "ResultStatus" }
    ) | Export-Csv $modifiedFile -NoTypeInformation

这就是 UTC 时间现在的样子。

enter image description here

2021-12-01T18:23:21
2021-12-01T18:23:21
2021-12-01T18:23:21

最佳答案

使用TimeZoneInfo.ConvertTime() :

# sample UTC datetime value
$dt = [datetime]::UtcNow

# define target time zone
$targettz = [System.TimeZoneInfo]::FindSystemTimeZoneById('Eastern Standard Time')

# convert to target timezone 
[System.TimeZoneInfo]::ConvertTime($dt, $targettz)

这适用于本地化和通用日期时间值。

如果您希望它在遇到本地化值时失败,请使用 ConvertTimeFromUtc():

# this will still work
$dt = [datetime]::UtcNow
[System.TimeZoneInfo]::ConvertTimeFromUtc($dt, $targettz)

# this will fail
$dt = [datetime]::Now
[System.TimeZoneInfo]::ConvertTimeFromUtc($dt, $targettz)

关于powershell - 如何使用 PowerShell 将 UTC 转换为 EST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70204020/

相关文章:

powershell - 在Powershell中,[string []]是什么类型的数据类型,何时使用?

powershell - 从 Shell 脚本向 PowerShell 传递命令

javascript - jquery-csv 使用 toArrays() 时丢失了 csv 文件的最后一项

python - 在 Python 中从 csv 中读取原始行和字典

arrays - 将Powershell中的对象重定向到其他功能

powershell - 如何使用 Powershell 将 .Net Web 应用程序部署到 Azure

powershell - Win32_服务 : Use SetSecurityDescriptor() from PowerShell

powershell - 从路径创建文件夹目录?

regex - TCL Regex 用于匹配 CSV 中的未转义引号

powershell - 确定脚本是否隐藏运行