成功后删除文件内容

问题描述 投票:1回答:2

我想为每个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

windows powershell powershell-v2.0 powershell-v3.0
2个回答
0
投票

这是我做的东西:

    $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”文本文件。


0
投票

要将新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"
© www.soinside.com 2019 - 2024. All rights reserved.