【问题标题】:Handling errors when querying computer accounts查询计算机帐户时的错误处理
【发布时间】:2015-08-18 22:09:47
【问题描述】:

我正在使用this script 检索计算机列表的 OU。当计算机不存在时,我得到一个错误:

Cannot index into a null array.
At C:\tools\scripts\get-OU5.ps1:35 char:5
+     $dn = $result.Properties["distinguishedName"]
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

当我手动搜索域中的计算机时,它不存在。此外,在发生错误后,它会列出它从最后一台计算机接收到的先前 OU 值,作为给出错误的这台计算机的结果。

我知道 PowerShell 中有错误处理能力,但我只是不确定将错误处理放在哪里,然后将其作为结果报告到输出中。

【问题讨论】:

  • 如果你有 ActiveDirectory 模块,你可以在一行中完成所有这些。获取-ADComputer -Filter * |选择专有名称。如果你想编辑他的脚本,很可能 $result 在第 35 行是 $null。所以尝试更改为 if ((!$?) -or (-not $result) { return }

标签: powershell active-directory


【解决方案1】:

我将使用以下脚本来检索信息。它使用 PowerShell 中内置的错误处理功能:

function Get-ComputerProperties{
    [CmdletBinding()]
    #requires -version 3
    param(
        [parameter(ParameterSetName = "ComputerName", Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
        $ComputerName
    )

    begin{
        Import-Module ActiveDirectory

        function Get-ADParent ([string] $dn) {
            $parts = $dn -split '(?<![\\]),'
            $parts[1..$($parts.Count-1)] -join ','
        }

    }
    process {
        $result = $Null
        try{
            $result = Get-ADComputer -Filter {Name -eq $ComputerName} -ErrorAction Stop
            if($result){
                New-Object PSObject -Property @{"Name" = $ComputerName; "OU" = (Get-ADParent $result.DistinguishedName)}
            }
        } catch {
            Write-Warning "Error while retrieving Computer properties for ComputerName $Computername ($($_.Exception.Message))"
        }

    }

    end{
        Remove-Module ActiveDirectory
    }
}

您可以通过以下方式使用该脚本:

Get-ComputerProperties -ComputerName "Computer1"

"Computer1","Computer2" | Get-ComputerProperties

或使用文本文件:

Get-Content "C:\computers.txt" | %{ Get-ComputerProperties }

【讨论】:

  • 这个可以和电脑列表一起使用吗?我大概有 100 台服务器要检查。
  • 当然,我已经在我的回答中添加了这种可能性。
猜你喜欢
  • 1970-01-01
  • 2018-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多