Powershell,检查文件中包含的对象是否多于列表中的对象
我正在创建一个脚本,在目录中的文件中循环,读取它们,并检查它们是否有不在允许列表中的组 到目前为止,我得到的是:Powershell,检查文件中包含的对象是否多于列表中的对象,powershell,scripting,Powershell,Scripting,我正在创建一个脚本,在目录中的文件中循环,读取它们,并检查它们是否有不在允许列表中的组 到目前为止,我得到的是: $allowedGroups = 'group1', 'group2', 'group3' $AssignedValue = Get-ChildItem -path "C:\Users\user\Desktop\ExampleComputer\*.txt" ForEach ($file in $AssignedValue) { $contents = Get-Content
$allowedGroups = 'group1', 'group2', 'group3'
$AssignedValue = Get-ChildItem -path "C:\Users\user\Desktop\ExampleComputer\*.txt"
ForEach ($file in $AssignedValue) {
$contents = Get-Content $file | select -skip 6
if ($contents -notin $allowedGroups ){
$contents | Out-file -Append -FilePath'C:\Users\user\Desktop\listofcomputers.txt'}
}
我想做的是,如果一个文件包含AlloweGroup列表中不包含的组,它会将其输出到一个文件中。但是,它只是输出所有文件内容。我在将文件名添加到输出时也遇到了问题,我尝试的所有操作都没有输出文件名
谢谢大家! 您可以从
Foreach
循环中的$file
变量中获取文件名。要查找不允许的组的名称,请使用-notcontains
运算符。并使用-join
运算符将这些名称的数组组合成一个字符串大概是这样的:
$allowedGroups = 'group1', 'group2', 'group3'
$AssignedValue = Get-ChildItem -path "C:\Users\user\Desktop\ExampleComputer\*.txt"
ForEach ($file in $AssignedValue) {
$contents = Get-Content $file | select -skip 6
$notAllowedGroups = $contents | where {$allowedGroups -notcontains $_}
if ($notAllowedGroups.Count -gt 0) {
$reportForFile = $file.Name + ": " + ($notAllowedGroups -join ',')
$reportForFile | Out-file -FilePath 'C:\Users\user\Desktop\listofcomputers.txt' -Append
}
}
我认为您的问题在于,
$contents
是一个数组,而不仅仅是一个元素。您可能需要在所有$contents
中进行另一个循环,以检查每个元素是否在$alloweGroups
中。忽略最后一条注释,我刚刚搞乱了一个变量的拼写,代码工作得很好,谢谢!