Can't use Get-ADGroup in foreach loop Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag?How do you get the index of the current iteration of a foreach loop?How does the Java 'for each' loop work?Accessing the index in 'for' loops?How do I loop through or enumerate a JavaScript object?JavaScript closure inside loops – simple practical exampleHow do I break out of nested loops in Java?Calling remove in foreach loop in JavaLoop through an array in JavaScriptIs there a reason for C#'s reuse of the variable in a foreach?How does PHP 'foreach' actually work?

Why one of virtual NICs called bond0?

Gastric acid as a weapon

What makes black pepper strong or mild?

What are the motives behind Cersei's orders given to Bronn?

Why did the IBM 650 use bi-quinary?

Is there a documented rationale why the House Ways and Means chairman can demand tax info?

Is high blood pressure ever a symptom attributable solely to dehydration?

Is above average number of years spent on PhD considered a red flag in future academia or industry positions?

Output the ŋarâþ crîþ alphabet song without using (m)any letters

The logistics of corpse disposal

Do I really need recursive chmod to restrict access to a folder?

What do you call a plan that's an alternative plan in case your initial plan fails?

How to draw this diagram using TikZ package?

Stars Make Stars

Doubts about chords

I am not a queen, who am I?

What is the musical term for a note that continously plays through a melody?

How do I stop a creek from eroding my steep embankment?

How do I mention the quality of my school without bragging

When -s is used with third person singular. What's its use in this context?

How widely used is the term Treppenwitz? Is it something that most Germans know?

How discoverable are IPv6 addresses and AAAA names by potential attackers?

Are my PIs rude or am I just being too sensitive?

Is the Standard Deduction better than Itemized when both are the same amount?



Can't use Get-ADGroup in foreach loop



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?How do you get the index of the current iteration of a foreach loop?How does the Java 'for each' loop work?Accessing the index in 'for' loops?How do I loop through or enumerate a JavaScript object?JavaScript closure inside loops – simple practical exampleHow do I break out of nested loops in Java?Calling remove in foreach loop in JavaLoop through an array in JavaScriptIs there a reason for C#'s reuse of the variable in a foreach?How does PHP 'foreach' actually work?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I want to use a Get-ADGroup command in nested foreach loops. But somehow the command results nothing back. The command and filters are corect, as you can see it at the very bottom after the loops, the same instruction works there perfectly, for whatever reason.



$file = "\path"
$data = Import-Csv $file -Delimiter ";" -Encoding UTF7 |
select -First 5

Measure-Command
foreach ($item in $data )
$tiefe = $($item.'Tiefe')
$pfad = $($item.'Pfad')
$recht = $($item.'Recht')
$trustee = $($item.'trustee')

$LDAPDirectoryService = 'IP-Adresss'
$DomainDN = 'o=enterprise'

$LDAPFilter = "cn=$trustee"

$null = [System.Reflection.Assembly]::LoadWithPartialName('System.DirectoryServices.Protocols')
$null = [System.Reflection.Assembly]::LoadWithPartialName('System.Net')

$LDAPServer = New-Object System.DirectoryServices.Protocols.LdapConnection $LDAPDirectoryService
$LDAPServer.AuthType = [System.DirectoryServices.Protocols.AuthType]::Anonymous
$LDAPServer.SessionOptions.ProtocolVersion = 3
$LDAPServer.SessionOptions.SecureSocketLayer = $false

$Scope = [System.DirectoryServices.Protocols.SearchScope]::Subtree
$AttributeList = @('*')

$SearchRequest = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $DomainDN,$LDAPFilter,$Scope,$AttributeList

$groups = $LDAPServer.SendRequest($SearchRequest)
$groups

#Prüft ob Gruppe existiert
if ($groups.Entries.Count -eq 0)
Write-Host " Group not found!" `n -Foregroundcolor Red $LDAPFilter
#Speichert alle nicht gefundenen Gruppen zur manuellen Nachbearbeitung
Add-Content -Path \Path -Value "$LDAPFilter"


foreach ($group in $groups.Entries)
#Listet alle Member der oben übergebenen Gruppe auf
$users = $group.Attributes['member'].GetValues('string')

foreach ($user in $users)
Write-Host $user
#Hier den User zur AD Gruppe hinzufügen
Write-Host "user zur Gruppe hinzufügen $pfad-$recht" -ForegroundColor Red

# This little Boy doesnt work
Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"'




# Here the command works without a fault
Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"' |
where $_.Description -like "*$pfad" -and $_.Name.EndsWith($recht)









share|improve this question
























  • I'm not sure why the one is working rather than the other, but my question to you is, why do you need it there? You already have access to a group because you are inside the foreach loop. You should be able to run Add-ADGroupMember -Identity $group -Members $user. Also, are you doing this with a full Active Directory domain, or an LDS? I might be missing a thing or two from your post though.

    – Joseph
    Mar 22 at 9:27











  • Its a bit tricky, I try to migrate Secrurity Groups from an LDS to AD.

    – Tobias Huprich
    Mar 22 at 9:29











  • So the $group value is the LDS Group Name, but now I need the AD Name to add these Users.

    – Tobias Huprich
    Mar 22 at 9:30

















0















I want to use a Get-ADGroup command in nested foreach loops. But somehow the command results nothing back. The command and filters are corect, as you can see it at the very bottom after the loops, the same instruction works there perfectly, for whatever reason.



$file = "\path"
$data = Import-Csv $file -Delimiter ";" -Encoding UTF7 |
select -First 5

Measure-Command
foreach ($item in $data )
$tiefe = $($item.'Tiefe')
$pfad = $($item.'Pfad')
$recht = $($item.'Recht')
$trustee = $($item.'trustee')

$LDAPDirectoryService = 'IP-Adresss'
$DomainDN = 'o=enterprise'

$LDAPFilter = "cn=$trustee"

$null = [System.Reflection.Assembly]::LoadWithPartialName('System.DirectoryServices.Protocols')
$null = [System.Reflection.Assembly]::LoadWithPartialName('System.Net')

$LDAPServer = New-Object System.DirectoryServices.Protocols.LdapConnection $LDAPDirectoryService
$LDAPServer.AuthType = [System.DirectoryServices.Protocols.AuthType]::Anonymous
$LDAPServer.SessionOptions.ProtocolVersion = 3
$LDAPServer.SessionOptions.SecureSocketLayer = $false

$Scope = [System.DirectoryServices.Protocols.SearchScope]::Subtree
$AttributeList = @('*')

$SearchRequest = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $DomainDN,$LDAPFilter,$Scope,$AttributeList

$groups = $LDAPServer.SendRequest($SearchRequest)
$groups

#Prüft ob Gruppe existiert
if ($groups.Entries.Count -eq 0)
Write-Host " Group not found!" `n -Foregroundcolor Red $LDAPFilter
#Speichert alle nicht gefundenen Gruppen zur manuellen Nachbearbeitung
Add-Content -Path \Path -Value "$LDAPFilter"


foreach ($group in $groups.Entries)
#Listet alle Member der oben übergebenen Gruppe auf
$users = $group.Attributes['member'].GetValues('string')

foreach ($user in $users)
Write-Host $user
#Hier den User zur AD Gruppe hinzufügen
Write-Host "user zur Gruppe hinzufügen $pfad-$recht" -ForegroundColor Red

# This little Boy doesnt work
Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"'




# Here the command works without a fault
Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"' |
where $_.Description -like "*$pfad" -and $_.Name.EndsWith($recht)









share|improve this question
























  • I'm not sure why the one is working rather than the other, but my question to you is, why do you need it there? You already have access to a group because you are inside the foreach loop. You should be able to run Add-ADGroupMember -Identity $group -Members $user. Also, are you doing this with a full Active Directory domain, or an LDS? I might be missing a thing or two from your post though.

    – Joseph
    Mar 22 at 9:27











  • Its a bit tricky, I try to migrate Secrurity Groups from an LDS to AD.

    – Tobias Huprich
    Mar 22 at 9:29











  • So the $group value is the LDS Group Name, but now I need the AD Name to add these Users.

    – Tobias Huprich
    Mar 22 at 9:30













0












0








0








I want to use a Get-ADGroup command in nested foreach loops. But somehow the command results nothing back. The command and filters are corect, as you can see it at the very bottom after the loops, the same instruction works there perfectly, for whatever reason.



$file = "\path"
$data = Import-Csv $file -Delimiter ";" -Encoding UTF7 |
select -First 5

Measure-Command
foreach ($item in $data )
$tiefe = $($item.'Tiefe')
$pfad = $($item.'Pfad')
$recht = $($item.'Recht')
$trustee = $($item.'trustee')

$LDAPDirectoryService = 'IP-Adresss'
$DomainDN = 'o=enterprise'

$LDAPFilter = "cn=$trustee"

$null = [System.Reflection.Assembly]::LoadWithPartialName('System.DirectoryServices.Protocols')
$null = [System.Reflection.Assembly]::LoadWithPartialName('System.Net')

$LDAPServer = New-Object System.DirectoryServices.Protocols.LdapConnection $LDAPDirectoryService
$LDAPServer.AuthType = [System.DirectoryServices.Protocols.AuthType]::Anonymous
$LDAPServer.SessionOptions.ProtocolVersion = 3
$LDAPServer.SessionOptions.SecureSocketLayer = $false

$Scope = [System.DirectoryServices.Protocols.SearchScope]::Subtree
$AttributeList = @('*')

$SearchRequest = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $DomainDN,$LDAPFilter,$Scope,$AttributeList

$groups = $LDAPServer.SendRequest($SearchRequest)
$groups

#Prüft ob Gruppe existiert
if ($groups.Entries.Count -eq 0)
Write-Host " Group not found!" `n -Foregroundcolor Red $LDAPFilter
#Speichert alle nicht gefundenen Gruppen zur manuellen Nachbearbeitung
Add-Content -Path \Path -Value "$LDAPFilter"


foreach ($group in $groups.Entries)
#Listet alle Member der oben übergebenen Gruppe auf
$users = $group.Attributes['member'].GetValues('string')

foreach ($user in $users)
Write-Host $user
#Hier den User zur AD Gruppe hinzufügen
Write-Host "user zur Gruppe hinzufügen $pfad-$recht" -ForegroundColor Red

# This little Boy doesnt work
Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"'




# Here the command works without a fault
Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"' |
where $_.Description -like "*$pfad" -and $_.Name.EndsWith($recht)









share|improve this question
















I want to use a Get-ADGroup command in nested foreach loops. But somehow the command results nothing back. The command and filters are corect, as you can see it at the very bottom after the loops, the same instruction works there perfectly, for whatever reason.



$file = "\path"
$data = Import-Csv $file -Delimiter ";" -Encoding UTF7 |
select -First 5

Measure-Command
foreach ($item in $data )
$tiefe = $($item.'Tiefe')
$pfad = $($item.'Pfad')
$recht = $($item.'Recht')
$trustee = $($item.'trustee')

$LDAPDirectoryService = 'IP-Adresss'
$DomainDN = 'o=enterprise'

$LDAPFilter = "cn=$trustee"

$null = [System.Reflection.Assembly]::LoadWithPartialName('System.DirectoryServices.Protocols')
$null = [System.Reflection.Assembly]::LoadWithPartialName('System.Net')

$LDAPServer = New-Object System.DirectoryServices.Protocols.LdapConnection $LDAPDirectoryService
$LDAPServer.AuthType = [System.DirectoryServices.Protocols.AuthType]::Anonymous
$LDAPServer.SessionOptions.ProtocolVersion = 3
$LDAPServer.SessionOptions.SecureSocketLayer = $false

$Scope = [System.DirectoryServices.Protocols.SearchScope]::Subtree
$AttributeList = @('*')

$SearchRequest = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $DomainDN,$LDAPFilter,$Scope,$AttributeList

$groups = $LDAPServer.SendRequest($SearchRequest)
$groups

#Prüft ob Gruppe existiert
if ($groups.Entries.Count -eq 0)
Write-Host " Group not found!" `n -Foregroundcolor Red $LDAPFilter
#Speichert alle nicht gefundenen Gruppen zur manuellen Nachbearbeitung
Add-Content -Path \Path -Value "$LDAPFilter"


foreach ($group in $groups.Entries)
#Listet alle Member der oben übergebenen Gruppe auf
$users = $group.Attributes['member'].GetValues('string')

foreach ($user in $users)
Write-Host $user
#Hier den User zur AD Gruppe hinzufügen
Write-Host "user zur Gruppe hinzufügen $pfad-$recht" -ForegroundColor Red

# This little Boy doesnt work
Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"'




# Here the command works without a fault
Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"' |
where $_.Description -like "*$pfad" -and $_.Name.EndsWith($recht)






arrays powershell loops foreach active-directory






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 10:05









Ansgar Wiechers

146k13135193




146k13135193










asked Mar 22 at 8:20









Tobias HuprichTobias Huprich

83




83












  • I'm not sure why the one is working rather than the other, but my question to you is, why do you need it there? You already have access to a group because you are inside the foreach loop. You should be able to run Add-ADGroupMember -Identity $group -Members $user. Also, are you doing this with a full Active Directory domain, or an LDS? I might be missing a thing or two from your post though.

    – Joseph
    Mar 22 at 9:27











  • Its a bit tricky, I try to migrate Secrurity Groups from an LDS to AD.

    – Tobias Huprich
    Mar 22 at 9:29











  • So the $group value is the LDS Group Name, but now I need the AD Name to add these Users.

    – Tobias Huprich
    Mar 22 at 9:30

















  • I'm not sure why the one is working rather than the other, but my question to you is, why do you need it there? You already have access to a group because you are inside the foreach loop. You should be able to run Add-ADGroupMember -Identity $group -Members $user. Also, are you doing this with a full Active Directory domain, or an LDS? I might be missing a thing or two from your post though.

    – Joseph
    Mar 22 at 9:27











  • Its a bit tricky, I try to migrate Secrurity Groups from an LDS to AD.

    – Tobias Huprich
    Mar 22 at 9:29











  • So the $group value is the LDS Group Name, but now I need the AD Name to add these Users.

    – Tobias Huprich
    Mar 22 at 9:30
















I'm not sure why the one is working rather than the other, but my question to you is, why do you need it there? You already have access to a group because you are inside the foreach loop. You should be able to run Add-ADGroupMember -Identity $group -Members $user. Also, are you doing this with a full Active Directory domain, or an LDS? I might be missing a thing or two from your post though.

– Joseph
Mar 22 at 9:27





I'm not sure why the one is working rather than the other, but my question to you is, why do you need it there? You already have access to a group because you are inside the foreach loop. You should be able to run Add-ADGroupMember -Identity $group -Members $user. Also, are you doing this with a full Active Directory domain, or an LDS? I might be missing a thing or two from your post though.

– Joseph
Mar 22 at 9:27













Its a bit tricky, I try to migrate Secrurity Groups from an LDS to AD.

– Tobias Huprich
Mar 22 at 9:29





Its a bit tricky, I try to migrate Secrurity Groups from an LDS to AD.

– Tobias Huprich
Mar 22 at 9:29













So the $group value is the LDS Group Name, but now I need the AD Name to add these Users.

– Tobias Huprich
Mar 22 at 9:30





So the $group value is the LDS Group Name, but now I need the AD Name to add these Users.

– Tobias Huprich
Mar 22 at 9:30












1 Answer
1






active

oldest

votes


















0














I still dont know why but I found a solution working for me.



$AD = Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"' | where $_.Description -like "*$pfad" -and $_.Name.endswith($recht) 
write-Host $AD.Name -ForegroundColor Yellow


Maybe someone can tell me why I have to declare get-ADGroup as a variable in the Loop, but outside its working without it.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55295489%2fcant-use-get-adgroup-in-foreach-loop%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I still dont know why but I found a solution working for me.



    $AD = Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"' | where $_.Description -like "*$pfad" -and $_.Name.endswith($recht) 
    write-Host $AD.Name -ForegroundColor Yellow


    Maybe someone can tell me why I have to declare get-ADGroup as a variable in the Loop, but outside its working without it.






    share|improve this answer



























      0














      I still dont know why but I found a solution working for me.



      $AD = Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"' | where $_.Description -like "*$pfad" -and $_.Name.endswith($recht) 
      write-Host $AD.Name -ForegroundColor Yellow


      Maybe someone can tell me why I have to declare get-ADGroup as a variable in the Loop, but outside its working without it.






      share|improve this answer

























        0












        0








        0







        I still dont know why but I found a solution working for me.



        $AD = Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"' | where $_.Description -like "*$pfad" -and $_.Name.endswith($recht) 
        write-Host $AD.Name -ForegroundColor Yellow


        Maybe someone can tell me why I have to declare get-ADGroup as a variable in the Loop, but outside its working without it.






        share|improve this answer













        I still dont know why but I found a solution working for me.



        $AD = Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"' | where $_.Description -like "*$pfad" -and $_.Name.endswith($recht) 
        write-Host $AD.Name -ForegroundColor Yellow


        Maybe someone can tell me why I have to declare get-ADGroup as a variable in the Loop, but outside its working without it.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 22 at 9:56









        Tobias HuprichTobias Huprich

        83




        83





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55295489%2fcant-use-get-adgroup-in-foreach-loop%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현