Out-File 不会显示所有 Out-File 命令

Out-File Won't display all Out-File commands

我有一个简短的问题。我想要我必须在文本文档中打印的信息。问题是我唯一看到打印的是一行 "No Direct Reports Listed"。为什么会这样?

$results = Get-ADUser -Properties enabled,displayname,sn,name,surname `
             -Filter {name -like "*"} |
           Select name,sn,displayname,enabled,surname
$name    = $user.Name
$owned   = Get-Adgroup -Properties description,managedby `
             -Filter {managedby -eq $name}

foreach ($user in $results) {
  if ($user.enabled -eq $false) {
    if ($owned -eq $Null) {
      $user.name + "|" + $user.DisplayName + "|"  +
        "Managing Group: None Found " + "|" +
        " Group Description: None Provided " | Out-File $output
    } elseif (($description -eq " ") -or ($description -eq $Null)) {
      $user.name + "|" + $user.DisplayName + "|"  + "Managing Group: " +
        $_.name + "|" + " Group Description: None Provided " | Out-File $output
    } else {
      $user.name + "|" + $user.DisplayName + "|"  + "Managing Group: " +
        $_.name + "|" + " Group Description: " +
        ($_.description -replace "`r`n", "  ") | Out-File $output
    }

    $directReports = Get-ADUser -Identity $name -Properties directreports |
                     Select -ExpandProperty directreports

    foreach ($ID in $directReports) {
      if ($ID -ne $Null) {
        $directreports = get-aduser $ID
        "Direct Reports Listed Under User: " + "|" + $directreports.name |
          Out-File $output
      } else {
        "No Direct Reports Listed" | Out-File $output
      }
    }#foreach
  }#if
}#foreach

发送到 Out-File 的代码中的最后一个输出(在本例中为 "No Direct Reports Listed" | Out-File $output)将是您在文件中看到的内容。在您当前的设置中,您需要使用 -Append 开关。来自 TechNet

-Append

Adds the output to the end of an existing file, instead of replacing the file contents.

您也可以使用默认的 Add-Content cmdlet。

由于默认情况下 Out-FileAdd-Content 的编码不同,请注意您可能还需要调整 -Encoding

旁注

并不是说它非常复杂,但是当 If 语句开始失控时,使用 switch 语句可以更直观地处理。