【发布时间】:2018-09-06 11:22:12
【问题描述】:
我正在尝试创建一个简单的 PowerShell 脚本,该脚本将查看来自文本文件的 Active Directory 组列表,然后在 Active Directory 中搜索组(无论类型如何),然后获取每个组中的成员列表组,然后将每个用户的“名称”属性输出到输出文本文件。 现在我几乎已经完成了除了最后一部分之外的所有事情。当它将名称输出到文本文件时,它只向文件输出一个名称,而不是其他 300 个。但是,如果我取消输出函数,脚本只会在控制台中输出我想要的所有名称。有人可以解释为什么我完成这项工作的方法不起作用吗?我真的很好奇为什么我不能以我想要的方式将输出定向到文件。 此外,脚本正确循环所有内容,我知道它也找到了组(我知道这一点,因为当我查看文本文件时,我看到每个文件都有一个条目),但脚本会遍历前 8 个组并开始抛出错误,指出它找不到它应该循环通过的特定组。但它已经找到了它们并且只为每个文件输出了一个条目。这是为什么呢?
我对我的第一个问题的答案更感兴趣,因为脚本仍然可以正确执行它应该做的事情。
所以,重申一下,我想知道为什么脚本只向文件输出一个名称,而它应该为每个组输出 300+ 个名称。
##This is variable that will hold the file path for the list of Active Directory Groups##
$file='C:\Users\me\Desktop\DL_Names.txt';
##Command to dump the list into a variable##
$DLnames=get-content $file;
##This is the variable to hold the path for where the output files are to be placed##
[string]$path='C:\Users\me\Desktop\DL_repository\';
##Loop through the variable and for each entry preform the instruction listed##
foreach ($name in $DLnames)
{
##These two variables are used to create the file name for the output files##
[string]$filename=$name+'.txt';
[string]$Fullpath=$path+$filename;
#This variable is used to determine if the groups exists in Active Directory##
$verifygroupexists = Get-ADGroup -Identity $name;
##This is the if statement that is used to determine if the group exists in Active Directory##
if($verifygroupexists -eq $null)
{
##If the group doesnt exist, create a file and output the string to the file stating so with the group name##
##Still working on the removing portion of this, need help##
New-Item $fullpath -ItemType file;
[string]$error='AD Group'+' '+$name+' '+'does not exist';
$error | Out-File -filepath $Fullpath;
$Removeentry=$name;
$name.Remove($Removeentry);
}
else
{
##If the group does exist in Active Directory then create a new text file to be used for output.
New-Item $fullpath -ItemType file;
##Get the list of memebrs in the group and place them into a new variable##
$groupmember=get-adgroupmember -Identity $name;
##Now loop through each entry in the new variable and output to the text file each member's 'name' (A.K.A. Displayname)##
foreach ($user in $groupmember)
{
##This is where my issue is, its not outputting all of the names to the text file##
$displayname=get-aduser -identity $User.SamAccountName | select name | Out-File -filepath $Fullpath;
};
};
};
例如,输出总是如下所示:
名称
姓氏1
什么时候应该:
名称
姓氏1
姓氏2
姓氏3
姓氏4
姓氏5
等等等等等等
【问题讨论】:
-
"为什么脚本只向文件输出一个名称,而它应该为每个组输出 300+。" - 因为代码说要覆盖文件,输出单个用户。您需要将所有输出通过管道传输到
out-file,而不是一次一行。或者使用add-content避免覆盖。 -
@TessellatingHeckler 我如何将所有输出通过管道传输到文件中?我以为我已经这样做了。
-
$things | foreach-object { ... } | out-file将所有对象通过管道传输到一个文件,而不是$things | foreach-object { ...| out-file }将每个对象通过管道传输到新文件(覆盖之前的文件)。
标签: powershell active-directory text-files multiple-users displayname-attribute