我正在开发一个Powershell脚本(使用GUI),以帮助我的同事更容易地找到冗余和禁用的AD帐户。
这是一个小预览..。
$props = "Name, Enabled, PasswordExpired, Company,passwordNeverExpires, Office"
$propsAsArray = $props -split ',\s*'
Get-ADUser -filter * -properties $propsAsArray | where {$_.Enabled -eq $true} | where {$_.PasswordNeverExpires -eq $false}| where {$_.passwordexpired -eq $false} | Select-Object $propsAsArray | Export-csv -Path "C:\report.csv"
这一切都很好,并输出一个CSV报告。
不过,问题是如何将AD帐户状态的所有可能组合和排列分配给变量,然后将变量替换为Get-ADUser cmdlet (取决于用户在GUI中单击哪个单选按钮)。
我试过了所有能想到的,但只有得到错误的Expressions are only allowed as the first element of a pipeline。
我确信$accountStatus = "where {$_.Enabled -eq $true} | where {$_.PasswordNeverExpires -eq $false}" (或微妙的变体)不是它的实现方式。
我对Powershell还比较陌生,我渴望获得经验。谢谢,威廉。
发布于 2021-03-14 18:08:34
您可以通过将每个条件与和
Get-ADUser -Filter * -Properties $propsAsArray | Where-Object {(($_.Enabled -eq $true) -and ($_.PasswordNeverExpires -eq $false)) -and ($_.passwordexpired -eq $false)} | Select-Object $propsAsArray | Export-csv -Path "C:\report.csv"但是,正如Olaf在评论中所指出的,更好的做法是已经使用了-Filter参数Get-ADUser。在这里,您可以使用类似的条件组合:
Get-ADUser -Filter {((Enabled -eq $true) -and (PasswordNeverExpires -eq $true)) -and (passwordexpired -eq $false)} -Properties $propsAsArray | Select-Object $propsAsArray | Export-csv -Path "C:\report.csv"发布于 2021-03-14 18:20:17
注意:这个答案解决了被问到的问题,使用了一个基于(**{ ... }**),脚本的广义 何地对象-based解决方案,但是在当前情况下,基于Get-ADUser的-Filter参数的基于字符串的解决方案更好,该解决方案在源端高效过滤,如托马斯的回答中的第二个命令所示。
将表示条件项的脚本块 ({ ... })数组存储在变量中,并根据用户的GUI选择,使用索引数组选择要在情境中应用的条件:
# All individual conditions to test, expressed as an array of script blocks.
# Note: No need for `-eq $true` to test Boolean properties, and
# `-eq $false` is better expressed via the `-not` operator.
$blocks =
{ $_.Enabled },
{ -not $_.PasswordNeverExpires },
{ $_.PasswordExpired }
# Select the subset of conditions to apply using AND logic, using
# an array of indices, based on the GUI selections.
$indices = 0..2 # e.g., all 3 conditions (same as: 0, 1, 2)
Get-ADUser -Filter * -properties $propsAsArray | Where-Object {
# The following is equivalent to combining the conditionals of interest
# with -and (AND logic):
foreach ($block in $blocks[$indices]) { # Loop over selected conditionals
if (-not (& $block)) { return $false } # Test, and return $false instantly if it fails.
}
$true # Getting here means that all conditions were met.
}注意每个块是如何通过& ( 呼叫操作员 )执行的。
https://stackoverflow.com/questions/66627700
复制相似问题