powershell - 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
解决方案
编辑:错误不仅在逻辑内,而且是一个错字:| 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
推荐阅读
- android - DAO:如何使用 Insert 的返回值
- tkinter - Tkinter 如何更改组合框小部件箭头图像
- python - 实现具有负对数似然损失的简单概率模型
- sql - SQL 从具有特定查询的 2 个表中选择
- javascript - React BrowserRouter不加载接受“/”确切路由的组件 - 路径定义
- c++ - 在 C++ 中,函数参数中的独立花括号是什么意思?
- php - 替换或覆盖php中的时间值
- python - Spotipy 刷新访问令牌 Oauth2
- flutter - TextField onChange 方法会触发 build 方法吗?
- reactjs - 我的函数返回一个对象而不是任务 JSON