繁体   English   中英

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

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

在尝试从 PS 将 lastLogon 日期写入数据库时,我得到 output 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")转换 output 的尝试到目前为止都失败了

我的 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格式的日期时间字符串 - 例如2021-10-10T21:14:40 - 您可以使用标准s格式说明符获得:

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 ,而不是访问由Select-Object调用创建的当前管道输入 object, $_上的.lastlogon属性

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM