如何将日期时间从 PowerShell 输出转换为 yyyy-MM-dd HH:mm:ss 格式

How to convert datetime from PowerShell output to yyyy-MM-dd HH:mm:ss format

在尝试从 PS 将 lastLogon 日期写入数据库时​​,我得到了输出 10-10-2021 21:14:40 但是当将其写入我的数据库 (MS SQL) 时,日期转换 1900-01-01 00:00:00.000 而不是 2021-10-10 21:14:40.000 和任何使用例如转换输出的尝试$DateStr = $lastLogon.ToString("yyyy-MM-dd HH:mm:ss.sss") 到目前为止失败了

我的PS脚本:

.....
Import-Module ActiveDirectory
Add-Type -AssemblyName System.Web

$EmploymentUser = Invoke-SQL -sqlCommand "select * from EmploymentUser where LastFlowEditDate Is Not NUll AND (EndDate Is Null OR EndDate > CURRENT_TIMESTAMP) AND StartDate < CURRENT_TIMESTAMP ORDER BY Initials;"

foreach($User in $EFP_EmploymentUser)
{
Get-ADUser $User.Initials -Properties lastLogon | Select @{Name="lastLogon";Expression={[datetime]::FromFileTime($_.'lastLogon')}}

    Invoke-SQL -sqlCommand "UPDATE EFP_EmploymentUser SET lastLogonAD  = '$($lastLogon)' WHERE ID like $($User.ID)"

}

谁能帮忙?

ISO 8601 format - e.g. 2021-10-10T21:14:40 - which you can obtain with the standard s format specifier 中使用日期时间字符串:

foreach ($user in $EFP_EmploymentUser) {

  $lastlogon = [datetime]::FromFileTime(
    (Get-ADUser $User.Initials -Properties lastLogon).lastlogon
  )

  Invoke-SQL -sqlCommand "
      UPDATE EFP_EmploymentUser
      SET lastLogonAD  = '$($lastLogon.ToString('s'))'
      WHERE ID like $($user.ID)
    "

}

使用 ISO 8601 格式字符串的优点是它根据定义 文化不变

一个简化的例子,使用Get-Date:

PS> (Get-Date).ToString('s')
2021-10-10T17:42:41

注意:如果Get-Date无论如何都涉及到,你可以更简单地使用它的-Format参数:

PS> Get-Date -Format s
2021-10-10T17:42:41

至于你试过的

您的代码的主要问题是您试图使用未定义的变量 $lastlogon,而不是访问 .lastlogon 属性 在当前管道输入对象 $_ 上,由您的 Select-Object 调用创建。

在字符串插值的上下文中(在 "..." 字符串中),未定义的 $lastlogon 变量扩展为 空字符串 ,这就是为什么SQL 命令最终分配了它支持的最早日期时间值,1900-01-01 00:00:00.000

此外,您的 Get-ADUser ... 语句未连接到 Invoke-SQL 调用,因此前者的输出 - 具有 calculated[=60 的 [pscustomobject] 实例=] .lastlogon 属性 通过 Select-Object 创建 - 只是通过了。