arrayspowershellcsvforeachsites

Check AD Site Existence


I would like to import sites in my Active Directory environment with a CSV containing sitenames:

Example of my CSV-input:

New York
Dallas
New Jersey

I want to make a script that checks the existence of the sites first before the actual creation process occurs. However, I'm having some trouble with checking the input of 2 arrays:

#Clear process
$ADsites = ""
$SitesFilter = ""
$CSV = ""

[array] $ADSites = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites 

$csv=Import-Csv c:\sites.csv -header "Site"

#Filtering the Sitenames
Foreach ($ADSite in $ADSites) {
    [array] $SitesFilter += $ADSite.Name
}

$CSV | Foreach-Object {
    if (??? -eq $_.Site) {
        Write-Host "Site" $_.Site "already exists" 
    } else {
        Write-Host "Site" $_.Site "is not found"
    }
}

How can I compare the content of the array $SitesFilter with the sitenames in the CSV-file?


Solution

  • Hope below script could help, you should use -in, which could tell if object is within an array

    [array] $ADSites = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites 
    
    $csv=Import-Csv c:\sites.csv -header "Site"
    
    #Get an site name string array
    $SitesFilter = @($ADSites | %{"$($_.Name)"}) 
    
    $CSV | Foreach-Object {
        if ($SitesFilter -contains $_.Site ){
                    Write-Host "Site $($_.Site) already exists" 
        } Else { Write-Host "Site $($_.Site) is not found" }
    }