使用PowerShell脚本查找过去的日期

使用PowerShell脚本查找过去的日期,powershell,date,Powershell,Date,我目前正在编写一个PowerShell脚本,该脚本将审核Active Directory用户并查找过期的用户。日期以“MM/dd/yyyy”格式保存在人力资源部的CSV文件中。我正在尝试编写一个脚本,将今天的日期与CSV文件中的日期进行比较。如果CSV中的日期超过当前日期,则需要禁用该用户 例如: $today = getdate -format "MM/dd/yyyy" $expiration = $_.'Expiration Date' if ($today -ge $expiratio

我目前正在编写一个PowerShell脚本,该脚本将审核Active Directory用户并查找过期的用户。日期以“MM/dd/yyyy”格式保存在人力资源部的CSV文件中。我正在尝试编写一个脚本,将今天的日期与CSV文件中的日期进行比较。如果CSV中的日期超过当前日期,则需要禁用该用户

例如:

$today = getdate -format "MM/dd/yyyy"

$expiration = $_.'Expiration Date'

if ($today -ge $expiration) {*disable user*} else {*expiration date not 
expired*}
这种方法给了我不准确的数据。我认为Powershell是将日期读取为常规数字,而不是月/日/年。有人知道解决这个问题的正确方法吗


谢谢大家!

简而言之,您正在比较两个字符串值,而不是两个datetime对象

使用format开关指示Get Date返回字符串值。 您希望将其保留为[datetime]对象,以便可靠地进行比较

要获取当前日期时间,可以使用[datetime]::now或只获取日期(无参数)


要从CSV强制转换数据,只需使用[datetime]$($.“过期日期”)

您需要做的第一件事是以您想要的格式从文本字符串对象解析CSV日期

$Expired_Date = [DateTime]::ParseExact($_.'expration date', "dd/MM/yyyy", $null) 
现在使用逻辑:

$Current_Date = Get-Date -format "MM/dd/yyyy"
如果日期大于当前日期,则禁用aduser 注意:如果您有一个用户列表,那么您应该使用foreach循环来迭代每个用户,并在循环内进行校验和


希望有帮助。

尝试将数据从csv转换为日期时间。类似于这样的内容:-$expiration=[DateTime]::ParseExact($u.'expration date','dd/MM/yyyyy',$null)我尝试了这段代码,但它仍然提供了不准确的数据。下面是我使用的一些代码:foreach($users中的user){Try{$termdate=[datetime]::ParseExact($user.'Termination Date-Current','MM/dd/yyyyy',$null)$Current_Date=Get Date-Format“MM/dd/yyyyyy”if($Current_Date-ge$termdate){write host“term Date pass-$termdate”-$termdate”-foreground黄色}其他{write host”Date“Date not pass-$termdate”-背景色绿色}}捕捉{}-我错过了什么吗。。。谢谢你的帮助@Leah_CyberPadawan:你在Wayne的评论中已经这么做了。谢谢你的评论。我可以使用以下代码:foreach($users中的user){$termdate=[datetime]$($user.'Termination Date-Current')$Current_Date=Get Date if($Current_Date-ge$termdate){write host“term Date pass-$termdate”}否则{write host“Date not pass-$termdate”}
If($Current_Date -ge $Expired_Date)
{
#Get the user name. You have not mentioned how you are getting the users' list
Disable-ADAccount -Identity "CN=UserName,OU=L1Engineers,OU=UserAccounts,DC=DOMAIN,DC=COM"
Write-Output "Account has been disabled for the user Username"
}
else
{
Write-Output "Account has not been expired"
}