i made this script to find all windows 10 machines which are not placed in the right OU, there is no action taken at this point - but i would like to move them once they had been found, we have over 30 country's and data centers so i would like to keep the OU string in the arrays, to keep the code to a minimal - how would one perform a move in this script? i could use some pointers.
$Script:OUBase = "OU=Countries,OU=Global,DC=internal"
Import-Module ActiveDirectory
$CountryDataCenter =
@(
[pscustomobject]@{Country="UK";DataCenter="CEN1"},
[pscustomobject]@{Country="UK";DataCenter="CEN2"}
)
Function GetWin10MachineAccounts($Country, $DataCenter){
#Build OUstring
$OUStringTarget = "*OU=Windows 10,OU=Computers,OU=" + $DataCenter + ",OU=" + $Country + "," + $Script:OUBase
$OUStringSource = "OU=Computers,OU=" + $DataCenter + ",OU=" + $Country + "," + $Script:OUBase
$countPC = ($Win10Computeraccounts).count
Write-Host "OU to search - " $OUStringSource -ForegroundColor Yellow
$Win10ComputerAccounts = Get-ADComputer -SearchBase $OUStringSource -Filter {(enabled -eq "true") -and (OperatingSystem -like "*Windows 10*")} -properties * | where {$_.DistinguishedName -notlike "$OUStringTarget"} | select CN -expandproperty Name
Return $Win10Computeraccounts
}
############### Main Script ##########################
##create empty array for use later
$DataArray = @()
ForEach ($Country in $CountryDataCenter)
{
$Win10Computeraccounts = GetWin10MachineAccounts $Country.Country $Country.DataCenter
$countPC = $Win10Computeraccounts.count
if(!$Win10Computeraccounts) {
write-host "No Windows 10 Computers are found in the container" $Country.Country $Country.DataCenter
}
foreach ($Computer in $Win10Computeraccounts){
Write-Host $Computer -ForegroundColor Red
#Store Data in foreach array
$DataArray += (Get-ADComputer $Computer )
Write-Host "$countPC" "Computers found in" $Country.Country $Country.DataCenter -ForegroundColor Green
}
}
$DataArray | Export-Csv "C:\log.csv" -Force
Use the Move-ADObject
cmdlet:
foreach($Country in $CountryDataCenter)
{
$OUStringTarget = "OU=Windows 10,OU=Computers,OU={0},OU={1},{2}" -f $Country.DataCenter,$Country.Country,$Script:OUBase
$Win10Computeraccounts = GetWin10MachineAccounts $Country.Country $Country.DataCenter
foreach ($Computer in $Win10Computeraccounts){
Move-ADObject -Identity $Computer -TargetPath $OUStringTarget
}
}