查询计算机帐户时处理错误

时间:2015-08-18 22:09:48

标签: powershell active-directory

我使用this script检索OU以获取计算机列表。当计算机不存在时,我收到错误:

var dataAdapter1 = new SqlDataAdapter
{
    UpdateBatchSize = updateBatchSize,
    InsertCommand = new SqlCommand(insertCommand1, dbConnection)
    {
        UpdatedRowSource = UpdateRowSource.None
    }
};
dataAdapter1 .InsertCommand.Parameters.Add("@Id", SqlDbType.Int, 0, "Id");  
dbConnection.Open();
dataAdapter1 .Update(dtSomeDataTable);
// This inserts data into table 1.
var dataAdapter2 = new SqlDataAdapter
{
    UpdateBatchSize = updateBatchSize,
    InsertCommand = new SqlCommand(insertCommand2, dbConnection)
    {
        UpdatedRowSource = UpdateRowSource.None
    }
};
var count = dataAdapter2.Update(dtSomeDataTable);
//This does not insert any records (or throws an exception) and variable count is always 0;

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

我知道PowerShell中存在错误处理功能,但我不确定将错误处理放在何处,然后将其作为输出结果报告。

1 个答案:

答案 0 :(得分:0)

我会使用以下脚本来检索信息。它使用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 }