[英]Searching Active Directory and exporting a list of names in mulitpule groups to a txt file for powershell
我试图创建一个简单的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
最后,Name2
最后,姓名3
最后,姓名4
最后,姓名5
等等等等
该行将为组中的每个用户调用,并且每次运行时,它将覆盖文件的内容。
$displayname=get-aduser -identity $User.SamAccountName | select name | Out-File -filepath $Fullpath;
如果将Out-File
替换为Add-Content
,那么该命令将追加到文件中。 如果您反复运行脚本,请确保首先使用Set-Content
清除文件。 您也不需要在此步骤中设置变量$displayname
的值:
Set-Content -Value "" -Path $Fullpath
get-aduser -identity $User.SamAccountName | select name | Add-Content -Path $Fullpath;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.