for each -

This topic contains 5 replies, has 5 voices, and was last updated by  Bob McCoy 2 years, 4 months ago.

  • Author
  • #36669


    I would like to check my computer accounts for a location value . If match skip else set location. think I am missing something line below but cant seem to figure it out

    (Get-ADComputer -ComputerName $computer -location "New York".
    Please help . Thanks!

    # Domain controller to be used
    $dc = (Get-ADRootDSE).dnshostname
    write-host "Using DC $dc"

    # Specify the OU where the accounts are located
    $logdetail = "C:\ADlogs\$DayofWeek-log.txt"
    $OUdn = "OU=test,OU=Administrative,DC=testlab,DC=COM"
    $Oucomps = Get-ADComputer -Filter {OperatingSystem -like "Windows 7*"} -SearchBase $oudn -Server $dc

    foreach ($computer in $Oucomps){
    if (Get-ADComputer -ComputerName $computer -location "New York"){
    write-host $computer "Computer location found. skip"

    Set-ADComputer $computer -Location "New York"

  • #36670

    Wilfredo Perez

    Your if statement has to compare the location to New York using the -eq

    $cn = Get-ADComputer -Identity computername -Properties *
    foreach($c in $cn){
        if($c.Location -eq "New York"){
        Write-host "All Good"
        Write-host "All Bad"
    Result: All Bad
  • #36684

    Michael Maher

    Hi Darren,

    You can do this on the pipeline too.

    Get-ADComputer -filter '-not Location -like "New York"' -SearchBase "OU=Test,DC=testlab,DC=com" | 
    Set-ADComputer -Location "New York"


  • #36685

    Paal Braathen

    I see that "-Properties *" is mentioned here. I would not recommend that you use a wildcard for this argument.

    I'm not sure how many properties this is valid for, but the IPv4Address is actually a DNS lookup and not an attribute set on the object. So you might experience that the cmdlet will be more time consuming when using wildcard.

    Therefore: Just ask for the properties that you actually want.

  • #36714

    Wilfredo Perez

    Paal is right on the -Properties with the wildcard. I did not catch that.

  • #36719

    Bob McCoy

    There's also no value to setting the domain controller $dc variable. You only using it in a get-adcomputer cmdlet. All the DCs will have the replicated data. There's no value added here.

You must be logged in to reply to this topic.