繁体   English   中英

在 PowerShell 中将字符串表达式转换为日期类型

[英]Convert string expression to date type in PowerShell

我在PS中有以下代码:

Connect-AzureAD 
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent 
Get-AzureADUser -All:$true |Select ObjectId,UserPrincipalName,@{Name='ExpirationDate'; Expression={(Get-AzureADUserExtension -ObjectId $_.ObjectId).Get_Item("createdDateTime")}} 
| Export-CSV "$PSScriptRoot\userslist.csv"
Disconnect-AzureAD

我想将字符串createdDateTime转换为 dateTime 格式,所以我可以添加 +60 天( .AddDays(60)) 我尝试不进行转换,但没有成功。

Expression={(...).Get_Item("createdDateTime")}}

我也尝试使用 function [datetime]::ParseExact但我做错了(控制台中没有错误),因为 output 中的列是空白的。

请指教

编辑这是我运行帕梅拉给出的整个脚本后得到的。 控制台没有错误。 任何想法为什么会这样?

在此处输入图像描述

尝试使用您的代码并获得时间,它看起来像“2/16/2021 5:55:03 AM”:

在此处输入图像描述

所以我用'M/d/yyyy H:mm:ss tt'格式化字符串。

$string = "2/16/2021 5:55:03 AM"
[Datetime]::ParseExact($string, 'M/d/yyyy H:mm:ss tt', $null)

在此处输入图像描述

正如您在评论中所说,您的 CreationDate 就像“19.10.2020 13:55:29”,所以dMyyyy H:mm:ss应该可以工作(不确定您的 M 或 MM,您可以查看更多 CreationDate)。

格式化日期时间并添加 60 天:

Get-AzureADUser -All:$true |Select ObjectId,UserPrincipalName,@{Name='ExpirationDate'; Expression={[Datetime]::ParseExact((Get-AzureADUserExtension -ObjectId $_.ObjectId).Get_Item("createdDateTime"), 'd.M.yyyy H:mm:ss', $null).AddDays(60)}}

在此处输入图像描述

暂无
暂无

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

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