我有一个存储在文本文件中的用户列表。我正在尝试更新文本文件,以便删除与 $NotExpiring users 变量匹配的任何用户,该变量是一个集合。如果需要从文本文件中删除多个用户,我就是不知道如何正确更新文本文件。
下面是完整的功能。您可以忽略其中的大部分内容只需查看#Stuck Here 以了解重点。
function Get-NotExpiring{
$NotExpiring=New-Object System.Collections.Generic.List[System.Object]
$MatchedUser=New-Object System.Collections.Generic.List[System.Object]
$textfiles = Get-ChildItem $email_dir
#Day of Span
$Days="20"
#Settings
$Date=Get-Date ((Get-Date).adddays($Days))
$Users=Get-ADUser -filter {(Enabled -eq $True) -and (PasswordNeverExpires -eq $False)} -Properties SamAccountName, DisplayName, msDS-UserPasswordExpiryTimeComputed, Mail | Where-Object { $_.DisplayName -ne $nul -and ($_."msDS-UserPasswordExpiryTimeComputed" -gt ($NotExpDate.ToFileTime()))} | Select SamAccountName, Mail, DisplayName,@{Name="ExpiryDate";Expression={([datetime]::fromfiletime($_."msDS-UserPasswordExpiryTimeComputed")).DateTime}}
#Magic
foreach ($Entry in $Users) {
$EntryDate = Get-date($Entry.ExpiryDate)
if ($EntryDate -gt $Date){
$Account = $Entry.SamAccountName
$ExpDate = $Entry.ExpiryDate
$NotExpiring.add($Account)
}
}
#STUCK HERE
foreach($file in $textfiles){
foreach ($user in $NotExpiring){
if((Get-Content "$email_dir\$file") -contains $user){
$temp_get = Get-Content $email_dir\$file | where {$_ -notmatch $user}
}}}
$temp_get}
我在下面尝试过,但如果超过一个用户 $NotExpiring 也在现有文本文件中,它似乎不起作用。任何帮助,将不胜感激。我知道这是一个简单的修复,但我似乎无法弄清楚。
Get-Content $email_dir\$file | where {$_ -notmatch $user} | Set-Content <path>.txt
我能够使用以下解决方案完全实现我所需要的。
foreach($file in $textfiles){ foreach ($user in $NotExpiring){
if((Get-Content "$email_dir\$file") -contains $user){
$MatchedUser.add($user)
}}
Get-Content "$email_dir\$file" | Where {$MatchedUser -NotContains $_ } | Set Content "$temp_dir\$file"
Copy-Item -path "$temp_dir\$file" -Destination "$email_dir\$file" -ErrorAction SilentlyContinue }
基本上,您正在尝试匹配两个数组。和where
你一起做foreach
对象。现在您必须将单个对象$_
与数组匹配$user
。
用:
...| where {$_ -notin $user}
或者
...| where {$user -notcontains $_}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句