Find what Computers are in Which Site

This topic contains 3 replies, has 4 voices, and was last updated by Profile photo of Dan Potter Dan Potter 1 year, 2 months ago.

  • Author
  • #38315
    Profile photo of Robert King
    Robert King

    I've been working the below code and can't seem to get the Sites to populate into the csv...any help would really be appreciated.

    #Import Module
    Import-Module ActiveDirectory
    #Set Variables
    $Domain = (Get-ADDomain).distinguishedname
    $OU = "CN=Computers,$Domain"
    $Logfile = "C:\Logs\ComputerSiteAssignments.csv"
    # Retrieve Site
    $GetSite = Get-ADComputer -Filter * -SearchBase $OU -Property * | foreach {
        nltest /server:$_.Name /dsgetsite
    #Get Computer information and format
    $Computer = @{}
    $Computer = Get-ADComputer -Filter * -SearchBase $OU -Property Name,OperatingSystem,Description,IPv4Address | foreach {
        $HostName = $_.Name
        $OS = $_.OperatingSystem
        $Description = $_.Description
        $IP = $_.IPv4Address
        $Sites = $GetSite
        OU = $OU
        Name = $HostName
        OS = $OS
        Description = $Description
        IP = $IP
        Site = $Sites
    # Export Logfile to CSV for review
    $Computer | Export-Csv $logfile -NoTypeInformation
  • #38316
    Profile photo of Anthony Stringer
    Anthony Stringer

    this may not be the only issue, but try using this command instead

    nltest /server:$($_.Name) /dsgetsite
  • #38339
    Profile photo of Rob Simmers
    Rob Simmers

    First, I would recommend making your nltest command a function because it's not a native Powershell command the results might not look like you expect and probably need to be parsed. Luckily, for you, someone had already created a function (link in the function). Also, rather than looping through the computers and manually generating an object, try using calculated properties to get the site information. This is not pseudo-code, not tested, but should be pretty close to what you are looking for:

    function Get-ComputerSite($ComputerName){
       $site = nltest /server:$ComputerName /dsgetsite 2>$null
       if($LASTEXITCODE -eq 0){ $site[0] }
    #Import Module
    Import-Module ActiveDirectory
    #Set Variables
    $Domain = (Get-ADDomain).distinguishedname
    $OU = "CN=Computers,$Domain"
    $Logfile = "C:\Logs\ComputerSiteAssignments.csv"
    $Computer = Get-ADComputer -Filter * -SearchBase $OU -Property Name,OperatingSystem,Description,IPv4Address | 
    Select Name, 
           @{Name="ADSite";Expression={Get-ComputerSite -ComputerName $_.Name}}
    $Computer | Export-Csv $logfile -NoTypeInformation
  • #38342
    Profile photo of Dan Potter
    Dan Potter

    It's also in here.


You must be logged in to reply to this topic.