【问题标题】:PowerShell CSV Not Exporting Missing Active Directory ObjectsPowerShell CSV 未导出丢失的 Active Directory 对象
【发布时间】:2017-03-17 00:23:37
【问题描述】:

之前我尝试制作一个 powershell 脚本来比较文本文件中的资产标签与 AD 中的计算机名称,这是成功的。但是,当在 AD 中找不到资产时,它只会跳过该行并继续下一行。找不到的资产不会导出到 CSV 文件中。

有没有办法让它在 CSV 文件中打印丢失的资产,以及资产标签旁边的“资产未找到”之类的消息?我尝试使用这条线,但所做的只是在两行之间添加空格。

if ($_.samaccountname -notlike "*$line*") {"Asset does not exist in AD"}

代码:

Import-Module ActiveDirectory

   [Array]$Collection = foreach($line in Get-Content H:\AssetNames.txt)  {
        Get-ADComputer -Filter * -Property Description | Where {$_.samaccountname -Like "*$line*"} | Select Name, Description
        #if ($_.samaccountname -notlike "*$line*") {"Asset does not exist in AD"}
    }

$Collection | Export-Csv C:\test.csv -NoTypeInformation

【问题讨论】:

标签: powershell csv active-directory


【解决方案1】:

您的问题是您排除了 Get-ADComputer 过滤器中不匹配的资产,因此您无法知道它们何时不匹配。如果对变量执行此操作,则可以检查:

Import-Module ActiveDirectory

   [Array]$Collection = foreach($line in Get-Content H:\AssetNames.txt)  {
        $Match = Get-ADComputer -Filter * -Property Description | Where {$_.samaccountname -Like "*$line*"} | Select Name, Description
        if (!$Match) {
            "Asset $($_.samaccountname) does not exist in AD" | Out-File -FilePath "ErrorLog.txt" -Append
        } else {
            Write-Output $Match
        }
    }

$Collection | Export-Csv C:\test.csv -NoTypeInformation

【讨论】:

  • 嗨,马克,抱歉回复晚了。刚刚尝试过,但写入输出没有将丢失的资产写入 CSV 文件,在 AD 中找不到的任何资产都将替换为 CSV 文件中的空行。
  • 尝试删除 [array] 部分。
  • 试过了,还是一样。如果我让它写入一个单独的文本文件,那么丢失的资产确实会显示在该文本文件中。
猜你喜欢
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-22
  • 1970-01-01
相关资源
最近更新 更多