【问题标题】:Out-File Won't display all Out-File commandsOut-File 不会显示所有 Out-File 命令
【发布时间】:2015-01-02 13:22:38
【问题描述】:

我有一个简单的问题。我想要我必须在文本文档中打印的信息。问题是我看到打印的唯一内容是“未列出直接报告”这一行。为什么会这样?

$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

【问题讨论】:

    标签: powershell output


    【解决方案1】:

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

    -追加

    将输出添加到现有文件的末尾,而不是替换文件内容。

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

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

    旁注

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

    【讨论】:

    • switch 仅在您需要区分同一主题的不同值/范围时才有用。在这种情况下,比较完全有主题。更实质性的改进是从循环中完全删除Out-File 语句,将外部循环更改为ForEach-Object 循环,并将其通过管道传输到单个Out-File 语句:$results | ForEach-Object {...} | Out-File $output。这将避免重复附加到输出文件,从而提高整体性能。但是请注意,为此,$user 必须替换为 $_
    • @AnsgarWiechers 是的,你所说的 switch 是真的。在这种情况下,我会使用Switch($true) 来说明这一点。也只是试图回答这个问题。过去几次尝试为人们优化代码而被烧毁。
    • 感谢您的解释。我仍在学习 Powershell,老实说,我从来没有完全知道 -Append 在不使用时做了什么。现在我知道了,非常感谢您的解释。
    • Ansgar Wiechers :您能解释一下您是如何编辑我的代码以显示所有颜色的吗?我不知道你能做到这一点
    • @AlyssaCooke Behold。您也可以编辑您的问题以查看当前的降价代码,或单击其下方的“已编辑 XXX 前”链接以转到修订历史记录并单击那里的“并排降价”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 2013-12-08
    • 2023-02-02
    • 2023-02-24
    相关资源
    最近更新 更多