我想为每个OU运行相同的Powershell命令。 OU列表在文本文件中给出。
**Powershell command:**
run_script OU1
run_script OU2
**Text File:**
OU1
OU2
...
到目前为止,我写了以下逻辑:
$OUnames = Get-Content("C:\ouNames.txt");
foreach ($OU in $OUnames)
{
$output = run_script $OU
if($output -contains "success")
// then delete $OU from ouNames.txt
// and inlcude $OU in the file ouNamesAdded.txt
}
如何在OU
为特定的run_script $OU
返回success
之后从第一个文本文件中删除OU
。另外,如何将$OU
添加到另一个文件ouNamesAdded.txt
如何从OU
中拾取多个C:\ouNames.txt
,然后为多个OU并行运行run_script $OU
这是我做的东西:
$OUnames = Get-Content("C:\ouNames.txt")
foreach ($OU in $OUnames)
{
$output = run_script $OU
if($output -contains "success")
{
$OUs = Get-Content("C:\ouNames.txt")
$OUs -notmatch "$OU" | Out-File "C:\ouNames.txt"
$OU | Out-File "C:\ouNamesAdded.txt" -Append
}
}
此代码将遍历文本文件并在每个文件上运行“run_script”命令。如果成功,它将获取文件中与成功OU不匹配的所有文本,并将其写入文本文件,擦除成功运行的字符串。然后将成功的字符串写入新的“ouNamesAdded”文本文件。
要将新OU内容添加到新文件,可以使用Add-Content
:
$OU | Add-Content "ouNamesAdded.txt"
为了删除内容,我会在完成循环后执行此操作。如果您对命令满意,可以删除-whatif
参数。
Compare-Object -ReferenceObject (Get-Content ouNames.txt) -DifferenceObject (Get-Content ouNamesAdded.txt) -PassThru | Set-Content ouNames.txt -whatif
我不知道任何会从文件中删除一行的内容。如果要在每次迭代后从文件中删除OU,则需要执行以下操作:
# Execute within the if statement
Get-Content ouNames.txt -notmatch "^$OU$" | Set-Content ouNames.txt
# Or using the $OUNames array (more efficient)
$OUnames -notmatch "^$OU$" | Set-Content ouNames.txt
如果你想跟踪列表并进行实时删除,我会使用类似arraylist的东西:
# Run this before the loop code
$OUs = $OUnames.clone() -as [system.collections.arraylist]
# Run this within the if statement
$OUs.Remove($OU)
# After the loop completes, then write to the output file
$OUs | Set-Content "ouNamesAdded.txt"