首页 > 解决方案 > foreach 循环中的 where 语句,比较日期

问题描述

尝试导入包含姓名、电子邮件、终止日期、停止日期的用户列表,并首先检查停止日期或终止日期是否已过。

尝试添加 [datetime] 并使用 get-date $user.'stop date' 但没有任何运气。它似乎可以使用以下代码而没有相同的问题,或者我得到相同的错误,但它确实检查并写出其中一个值更大:

$StopFolder = Get-ChildItem C:\test\123\*.csv |sort LastWriteTime -descending|select -first 1
$Stoplist = Import-Csv $StopFolder -delimiter ';'

$CurrentDate = Get-Date
foreach($Date in $Stoplist){
if($CurrentDate -eq (get-date $Date.'Stop Date')){write-host Equal}

if($CurrentDate -gt (get-date $Date.'Stop Date')){write-host Greater}

if($CurrentDate -lt (get-date $Date.'Stop Date')){write-host Less}}

但同样的情况似乎不适用于下面,并且无法真正弄清楚为什么。我想我需要将它转换为日期,但不确定为什么它在上面而不是下面工作,也不知道如果 get-date 不起作用,如何准确地转换它。

$StopFolder = Get-ChildItem C:\test\123\*.csv |sort LastWriteTime -descending|select -first 1
$Stoplist = Import-Csv $StopFolder -delimiter ';'
$CurrentDate = Get-Date

foreach($User in $Stoplist|where($_.'stop date' -lt $CurrentDate)){

try{
    $Usermail = $User.'e-mail address'
    $Username = get-aduser -Filter "EmailAddress -eq '$Usermail'" -properties Enabled


        if($Username.enabled){
        echo $Username 'still exists and is NOT disabled' >> C:\NotDisabled.txt
        }

        if($Username.enabled -eq $false){
        echo $Username 'still exists and is disabled' >> C:\NotDeleted.txt 
        }
}
catch{continue}
}

预期结果是仅在当前用户停止日期小于当前日期时才启动循环。目前没有任何反应,删除 where 部分,其余部分似乎运行良好。

任何帮助深表感谢。

编辑:CSV 日期是这样的:

停止日期

01-02-2023
21-09-2019
21-01-2019
01-01-2019
01-01-2019

标签: powershell

解决方案


编辑:错误不仅在逻辑内,而且是一个错字:| where需要花括号>| where {}而不是括号。


创建一个日期'stop date'

(get-date -date $_.'stop date')

在一行中:

foreach($User in $Stoplist|where{(get-date -date $_.'stop date') -lt $CurrentDate}){...}

$Stoplist|where{(get-date -date $_.'stop date') -lt $CurrentDate}是一个单元,可以封装在括号中:

foreach($User in ($Stoplist|where{(get-date -date $_.'stop date') -lt $CurrentDate}) ){...}

$User in $Stoplist在管道周围没有括号|仅指最后一个对象$Stoplist


推荐阅读