从AD OU获取有关域计算机的特定信息

时间:2019-11-13 22:00:29

标签: powershell active-directory

我正在尝试获取计算机的名称,制造商和型号,以便我可以区分AD中超出保修范围的计算机。

我正在尝试通过获取计算机名称并将信息放在相应的.csv文件中来实现此目的,但这失败了,将1 ou放入多个.csv文件,然后移至第二个ou,是否做同样的事情?

$myMultiArray = @(("OU=Domain Controllers,DC=FABRIKAM,DC=COM"), 
("OU=Computers,DC=FABRIKAM,DC=COM"))
$myFileArray = @(("‪D:\VS-Code\Powershell\AD_Computer_Management\OUs\Domain 
Controllers.csv"),("‪D:\VS- 
Code\Powershell\AD_Computer_Management\OUs\Computers.csv"))


foreach ($MultiOU in $myMultiArray) {

    Get-ADComputer -Filter * -SearchBase $MultiOU -SearchScope 2 | Select-object Name | Out-File -FilePath "D:\VS-Code\Powershell\AD_Computer_Management\OUs\garbage.csv"

    For ($i = 0; $i – $myFileArray.Length - 1; $i++) {
            Write-Host $myMultiArray[$i]

            [string[]]$cnArray = Get-Content -Path 'D:\VS-Code\Powershell\AD_Computer_Management\OUs\garbage.csv'

            Write-Host $OU
            if ($i -eq $i) {
                    foreach($CN in $cnArray){
                    Get-WmiObject -Class:Win32_ComputerSystem -ComputerName $OU | Format-List -Property Name, Manufacturer, Model | Out-File -FilePath $myFileArray[$1]
                    }
            }
    }

}

我尝试了不同循环和if语句的多种变体。

2 个答案:

答案 0 :(得分:0)

我认为有两件事:

  

文件外-FilePath $ myFileArray [$ 1]

应该是:

Out-File -FilePath $myFileArray[$i]

而且您可能还需要附加:

Out-File -FilePath $myFileArray[$i] -Append

答案 1 :(得分:0)

您的代码中有几处错误,例如$i – $myFileArray.Length,应为$i –lt $myFileArray.Length
然后有Out-File -FilePath $myFileArray[$1]Bernard Moeskops一样。
同样,您的代码似乎想创建Domain Controllers.csvComputers.csv文件,而不管您当前所在的OU如何。

最后,您正在使用Out-File创建CSV文件,为了正确输出CSV,应使用Export-Csv cmdlet。

以下代码应执行您想要的操作:

$myOUArray  = "OU=Domain Controllers,DC=FABRIKAM,DC=COM", "OU=Computers,DC=FABRIKAM,DC=COM"
$myFilePath = "‪D:\VS-Code\Powershell\AD_Computer_Management\OUs"  # just the path for the output files is needed

foreach ($OU in $myOUArray) {
    # determine the file name from the OU we're in
    $fileName = if ($OU -match 'OU=Domain Controllers') { 'Domain Controllers.csv' } else { 'Computers.csv'}
    $filePath = Join-Path -Path $myFilePath -ChildPath $fileName

    Write-Host "Getting computer info from OU '$OU'"
    # get a string array of the computernames found in the OU
    $computers = Get-ADComputer -Filter * -SearchBase $OU -SearchScope Subtree | Select-Object -ExpandProperty Name

    # loop through this array to get the properties you want for 
    # each computer and store that as objects in the $result variable
    $result = foreach($machine in $computers){
        Get-WmiObject -Class:Win32_ComputerSystem -ComputerName $machine | Select-Object -Property Name, Manufacturer, Model
    }
    Write-Host "Creating file '$filePath'"
    # save the CSV file to disk
    $result | Export-Csv -Path $filePath -NoTypeInformation -Force
}