Cleaner way to export namesHow to Show All Domain Users & Their Group Membership (Active Directory)Multi Tenency Scenario with WAAD in AzureLocal Groups and MembersAudit local accounts status, name, fullname, group membership & descriptionPowershell script to list all users whose manager account is disabledGet-adgroupmember and Displaying nested group name and its members in and exported to CSV fileGet-ADgroupmember FSP accounts issueForeach loop to export file to excel with different name everyday using windows task to run the scheduleHow to export list of group and users to CSV?Test if function returns nothing powershell and return “No Results found”

Impact of throwing away fruit waste on a peak > 3200 m above a glacier

Travelling from Venice to Budapest, making a stop in Croatia

Found more old paper shares from broken up companies

Is a sentence true for two substructures also true for their intersection?

How to make rotated box text centered?

Are irregular workouts through the day effective?

Why is DC so, so, so Democratic?

My current job follows "worst practices". How can I talk about my experience in an interview without giving off red flags?

What is an Eternal Word™?

What happens when two cards both modify what I'm allowed to do?

How can I make sure my players' decisions have consequences?

Is an easily guessed plot twist a good plot twist?

A team with high solidarity

What's the explanation for this joke about a three-legged dog that walks into a bar?

Using "Kollege" as "university friend"?

Are symplectomorphisms of Weil–Petersson symplectic form induced from surface diffeomorphisms?

A Sincere Nurikabe Puzzle

Why is a dedicated QA team member necessary?

JavaScript Sort Stack Coding Challenge

If a check is written for bill, but account number is not mentioned on memo line, is it still processed?

Sci-fi short story: plants attracting spaceship and using them as a agents of pollination between two planets

Does Impedance Matching Imply any Practical RF Transmitter Must Waste >=50% of Energy?

High income and difficulty during interviews

ExactlyOne extension method



Cleaner way to export names


How to Show All Domain Users & Their Group Membership (Active Directory)Multi Tenency Scenario with WAAD in AzureLocal Groups and MembersAudit local accounts status, name, fullname, group membership & descriptionPowershell script to list all users whose manager account is disabledGet-adgroupmember and Displaying nested group name and its members in and exported to CSV fileGet-ADgroupmember FSP accounts issueForeach loop to export file to excel with different name everyday using windows task to run the scheduleHow to export list of group and users to CSV?Test if function returns nothing powershell and return “No Results found”






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















When I export my group data from exchange/AD I am left with the full domain name, including CN=, OU=, OU=, ect. Is there something I can change in my script to get it to export just the name, instead of having to go into excel and search and replace what I dont want?



#Written by Tekwhat 10-26-17
write-host "Group Memberships"
#Settings for file ouput
$fLocation = "D:Exchange ReportsO365 Reports"

import-module activedirectory

#Get OU
$OU = Read-Host -Prompt "Input the OU name to search: (0202 - Dev Bank)"

#create File to write report to:
$fName = $fLocation+$OU+" Group Memberships.csv"
$test = test-path $fName
if ($test -eq $True)

write-host "Removing Old File..." -ForeGroundColor Red
Remove-Item $fName

#Else
#
#New-Item $fName -type file
#
Write-host "Creating New File..." -ForeGroundColor darkgreen
New-Item $fName -type file


$SearchBase = "OU=$OU,OU=Hosted Exchange Customers,DC=Domain,DC=local"
$ADGroups = Get-ADGroup -Filter * -SearchBase $SearchBase | % [ADSI]("LDAP://$_")
 
$Members = @()
 
foreach ($ADGroup in $ADGroups)
              $Members += $ADGroup.Member
 

$Members | Select-Object AdGroup, Member | Export-Csv -Path $fname -NoType
write-host "Your file is located at " $fname -ForegroundColor DarkGreen


The export of above gives something like this:




"All Employees","CN=Test X User,OU=OUname,OU=Hosted Exchange
Customers,DC=Domain,DC=local"




Which I have to go into excel and search replace "CN=" and "OU=OUname,OU=Hosted Exchange
Customers,DC=Domain,DC=local" to have usable data.










share|improve this question

















  • 1





    i believe that CN=* stuff is called a distinguished name. if that is correct, then you can use something like Get-ADUser -Identity $DN_To_Check to get the use name/display-name as needed.

    – Lee_Dailey
    Mar 26 at 18:36











  • There are so many good scripts for this to be found.. Anyway, @Lee_Daily is correct about it being a DistinghuishedName. Don't try to regex your way through that, but use it as Identity parameter for the Get-ADObject cmdlet. That way you can determine if the member is a user or another group by looking at the returned object's ObjectClass property. See Get-ADObject

    – Theo
    Mar 26 at 21:00

















0















When I export my group data from exchange/AD I am left with the full domain name, including CN=, OU=, OU=, ect. Is there something I can change in my script to get it to export just the name, instead of having to go into excel and search and replace what I dont want?



#Written by Tekwhat 10-26-17
write-host "Group Memberships"
#Settings for file ouput
$fLocation = "D:Exchange ReportsO365 Reports"

import-module activedirectory

#Get OU
$OU = Read-Host -Prompt "Input the OU name to search: (0202 - Dev Bank)"

#create File to write report to:
$fName = $fLocation+$OU+" Group Memberships.csv"
$test = test-path $fName
if ($test -eq $True)

write-host "Removing Old File..." -ForeGroundColor Red
Remove-Item $fName

#Else
#
#New-Item $fName -type file
#
Write-host "Creating New File..." -ForeGroundColor darkgreen
New-Item $fName -type file


$SearchBase = "OU=$OU,OU=Hosted Exchange Customers,DC=Domain,DC=local"
$ADGroups = Get-ADGroup -Filter * -SearchBase $SearchBase | % [ADSI]("LDAP://$_")
 
$Members = @()
 
foreach ($ADGroup in $ADGroups)
              $Members += $ADGroup.Member
 

$Members | Select-Object AdGroup, Member | Export-Csv -Path $fname -NoType
write-host "Your file is located at " $fname -ForegroundColor DarkGreen


The export of above gives something like this:




"All Employees","CN=Test X User,OU=OUname,OU=Hosted Exchange
Customers,DC=Domain,DC=local"




Which I have to go into excel and search replace "CN=" and "OU=OUname,OU=Hosted Exchange
Customers,DC=Domain,DC=local" to have usable data.










share|improve this question

















  • 1





    i believe that CN=* stuff is called a distinguished name. if that is correct, then you can use something like Get-ADUser -Identity $DN_To_Check to get the use name/display-name as needed.

    – Lee_Dailey
    Mar 26 at 18:36











  • There are so many good scripts for this to be found.. Anyway, @Lee_Daily is correct about it being a DistinghuishedName. Don't try to regex your way through that, but use it as Identity parameter for the Get-ADObject cmdlet. That way you can determine if the member is a user or another group by looking at the returned object's ObjectClass property. See Get-ADObject

    – Theo
    Mar 26 at 21:00













0












0








0








When I export my group data from exchange/AD I am left with the full domain name, including CN=, OU=, OU=, ect. Is there something I can change in my script to get it to export just the name, instead of having to go into excel and search and replace what I dont want?



#Written by Tekwhat 10-26-17
write-host "Group Memberships"
#Settings for file ouput
$fLocation = "D:Exchange ReportsO365 Reports"

import-module activedirectory

#Get OU
$OU = Read-Host -Prompt "Input the OU name to search: (0202 - Dev Bank)"

#create File to write report to:
$fName = $fLocation+$OU+" Group Memberships.csv"
$test = test-path $fName
if ($test -eq $True)

write-host "Removing Old File..." -ForeGroundColor Red
Remove-Item $fName

#Else
#
#New-Item $fName -type file
#
Write-host "Creating New File..." -ForeGroundColor darkgreen
New-Item $fName -type file


$SearchBase = "OU=$OU,OU=Hosted Exchange Customers,DC=Domain,DC=local"
$ADGroups = Get-ADGroup -Filter * -SearchBase $SearchBase | % [ADSI]("LDAP://$_")
 
$Members = @()
 
foreach ($ADGroup in $ADGroups)
              $Members += $ADGroup.Member
 

$Members | Select-Object AdGroup, Member | Export-Csv -Path $fname -NoType
write-host "Your file is located at " $fname -ForegroundColor DarkGreen


The export of above gives something like this:




"All Employees","CN=Test X User,OU=OUname,OU=Hosted Exchange
Customers,DC=Domain,DC=local"




Which I have to go into excel and search replace "CN=" and "OU=OUname,OU=Hosted Exchange
Customers,DC=Domain,DC=local" to have usable data.










share|improve this question














When I export my group data from exchange/AD I am left with the full domain name, including CN=, OU=, OU=, ect. Is there something I can change in my script to get it to export just the name, instead of having to go into excel and search and replace what I dont want?



#Written by Tekwhat 10-26-17
write-host "Group Memberships"
#Settings for file ouput
$fLocation = "D:Exchange ReportsO365 Reports"

import-module activedirectory

#Get OU
$OU = Read-Host -Prompt "Input the OU name to search: (0202 - Dev Bank)"

#create File to write report to:
$fName = $fLocation+$OU+" Group Memberships.csv"
$test = test-path $fName
if ($test -eq $True)

write-host "Removing Old File..." -ForeGroundColor Red
Remove-Item $fName

#Else
#
#New-Item $fName -type file
#
Write-host "Creating New File..." -ForeGroundColor darkgreen
New-Item $fName -type file


$SearchBase = "OU=$OU,OU=Hosted Exchange Customers,DC=Domain,DC=local"
$ADGroups = Get-ADGroup -Filter * -SearchBase $SearchBase | % [ADSI]("LDAP://$_")
 
$Members = @()
 
foreach ($ADGroup in $ADGroups)
              $Members += $ADGroup.Member
 

$Members | Select-Object AdGroup, Member | Export-Csv -Path $fname -NoType
write-host "Your file is located at " $fname -ForegroundColor DarkGreen


The export of above gives something like this:




"All Employees","CN=Test X User,OU=OUname,OU=Hosted Exchange
Customers,DC=Domain,DC=local"




Which I have to go into excel and search replace "CN=" and "OU=OUname,OU=Hosted Exchange
Customers,DC=Domain,DC=local" to have usable data.







powershell office365 exchange-server






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 26 at 15:19









TekwhatTekwhat

1510 bronze badges




1510 bronze badges







  • 1





    i believe that CN=* stuff is called a distinguished name. if that is correct, then you can use something like Get-ADUser -Identity $DN_To_Check to get the use name/display-name as needed.

    – Lee_Dailey
    Mar 26 at 18:36











  • There are so many good scripts for this to be found.. Anyway, @Lee_Daily is correct about it being a DistinghuishedName. Don't try to regex your way through that, but use it as Identity parameter for the Get-ADObject cmdlet. That way you can determine if the member is a user or another group by looking at the returned object's ObjectClass property. See Get-ADObject

    – Theo
    Mar 26 at 21:00












  • 1





    i believe that CN=* stuff is called a distinguished name. if that is correct, then you can use something like Get-ADUser -Identity $DN_To_Check to get the use name/display-name as needed.

    – Lee_Dailey
    Mar 26 at 18:36











  • There are so many good scripts for this to be found.. Anyway, @Lee_Daily is correct about it being a DistinghuishedName. Don't try to regex your way through that, but use it as Identity parameter for the Get-ADObject cmdlet. That way you can determine if the member is a user or another group by looking at the returned object's ObjectClass property. See Get-ADObject

    – Theo
    Mar 26 at 21:00







1




1





i believe that CN=* stuff is called a distinguished name. if that is correct, then you can use something like Get-ADUser -Identity $DN_To_Check to get the use name/display-name as needed.

– Lee_Dailey
Mar 26 at 18:36





i believe that CN=* stuff is called a distinguished name. if that is correct, then you can use something like Get-ADUser -Identity $DN_To_Check to get the use name/display-name as needed.

– Lee_Dailey
Mar 26 at 18:36













There are so many good scripts for this to be found.. Anyway, @Lee_Daily is correct about it being a DistinghuishedName. Don't try to regex your way through that, but use it as Identity parameter for the Get-ADObject cmdlet. That way you can determine if the member is a user or another group by looking at the returned object's ObjectClass property. See Get-ADObject

– Theo
Mar 26 at 21:00





There are so many good scripts for this to be found.. Anyway, @Lee_Daily is correct about it being a DistinghuishedName. Don't try to regex your way through that, but use it as Identity parameter for the Get-ADObject cmdlet. That way you can determine if the member is a user or another group by looking at the returned object's ObjectClass property. See Get-ADObject

– Theo
Mar 26 at 21:00












2 Answers
2






active

oldest

votes


















1














I apologize if I am assuming incorrectly, but I believe you are having trouble with the output of the member property. You may use something like the following:



$SearchBase = "OU=$OU,OU=Hosted Exchange Customers,DC=Domain,DC=local"
$ADGroups = Get-ADGroup -Filter * -SearchBase $SearchBase -Properties Member,CN

$Members = @()
foreach ($ADGroup in $ADGroups)
$Members += $ADGroup.Member


One potential effect of the code above is that you will have an duplicate ADGroup names for each member. If that is not intended, then things will need to be changed.



I maintained a majority of your code, so I will explain what I changed:



($_ | Select-String -pattern "(?<=CN=).*?(?=,OU=|,DC=)").matches.value




  • $_ refers to the current pipeline object from $ADGroup.Member


  • Select-String selects a string from the pipeline input based on a regex match in this case. The regex text is passed to the -pattern parameter.


  • "(?<=CN=).*?(?=,OU=|,DC=)" is the regex (regular expression).


    • (?<=CN=): (?<=) is a positive lookbehind mechanism that looks for the string CN= behind the current position in the match.


    • .*? matches as few as possible characters (.) except newline characters


    • (?=,OU=|,DC=) uses the positive lookahead mechanism ((?=)) to find string ,OU= or (|) the string ,DC=.



  • .Matches is the Matches property of the Select-String output. It contains other properties that are useful for specifying regex capture groups or select from multiple matches. One such property is value, which contains the actual string match.

  • The lookahead and lookbehind mechanisms do not capture any matches. They are merely positional to control where you are in the match sequence.





share|improve this answer

























  • It does seem to be the member output, its spitting out the cn and stuff. I wonder if I tell it instead to pull the exchange name, instead of AD member, it might just spit out the name? In your example, does the cn and ou/dc inside ( ) make it not ouput it?

    – Tekwhat
    Mar 26 at 17:10











  • I am outputting everything between CN= and ,OU. For example, CN=Group Name,OU=OrgUnit,DC=domain would output Group Name. Is that what you are going for? I can add explanation if this output is your desired output.

    – AdminOfThings
    Mar 26 at 17:11












  • That is indeed the desired output. If its not too much trouble can you give a brief explanation of what that's doing? I am still a powershell, well programming for that matter, baby.

    – Tekwhat
    Mar 26 at 17:59











  • I added some explanation. I hope this helps and let me know if it is sufficient.

    – AdminOfThings
    Mar 26 at 18:15











  • Thank you for that, I attempted to add the code to my script, but now it doesn't output anything for the member.

    – Tekwhat
    Mar 26 at 19:13


















1














It seems like you are over engineering this, based on your end goal. Correct me if I am wrong. Yet, in looking at your code, and your end goal, this would be my take on it.



No need for Write-Host (except for the color stuff) just to send to the screen (Write-Output) is the default, so you don't specifically have to write that out either, but that's a style choice.



"Create OU based Group Memberships Report"

$fLocation = 'C:Temp'

# no need to do this as modules are auto imported since v3, but it does not hurt to have it here
# Import-Module -Name ActiveDirectory

# Use a GUI to provide an OU list to select from.
$OUName = Get-ADOrganizationalUnit -Filter '*' |
Select-Object -Property Name, DistinguishedName |
Out-GridView -Title 'Select the OU name to search' -PassThru

# Set a file name to use. 'spaces in files names are just bad', so remove them
$fName = "$(($OUName).Name)_OU_ADGroup_Membership.csv" -replace ' '

# Remove any report of the same name
If(Test-Path -Path "$fLocation$fName")

Write-Warning -Message "A previous version of the report file is in the destination folder. Removing the file!"
Remove-Item -Path "$fLocation$fName" -Force


# Collect OU, AD group and user data and create a new CSV file
Get-ADOrganizationalUnit -Identity $OUName.DistinguishedName |
ForEach
ForEach
$ADGroup = $PSItem.Name
Get-ADGroupMember -Identity $ADGroup


Write-Host "Your new report file is licated here: $fLocation$fName" -ForegroundColor Yellow
Import-Csv -Path "$fLocation$fName"

#Results

WARNING: A previous version of the report file is in the destination folder. Removing the file!
Your new report file is licated here: C:TempLabUsers_OU_ADGroup_Membership.csv

GroupName Name SamAccountName
--------- ---- --------------
...
TestUsers Test User001 testuser001
...





share|improve this answer

























  • I attempted to run this, and it comes back with "group.name is not found in DC=domain, OU=local" I tried changing it to -SeachBase 'SubOuHere' which gives me the drilled down list to select from, but im not sure why its throwing the above error with and without the -SearchBase added.

    – Tekwhat
    Mar 27 at 16:31













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%2f55360669%2fcleaner-way-to-export-names%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














I apologize if I am assuming incorrectly, but I believe you are having trouble with the output of the member property. You may use something like the following:



$SearchBase = "OU=$OU,OU=Hosted Exchange Customers,DC=Domain,DC=local"
$ADGroups = Get-ADGroup -Filter * -SearchBase $SearchBase -Properties Member,CN

$Members = @()
foreach ($ADGroup in $ADGroups)
$Members += $ADGroup.Member


One potential effect of the code above is that you will have an duplicate ADGroup names for each member. If that is not intended, then things will need to be changed.



I maintained a majority of your code, so I will explain what I changed:



($_ | Select-String -pattern "(?<=CN=).*?(?=,OU=|,DC=)").matches.value




  • $_ refers to the current pipeline object from $ADGroup.Member


  • Select-String selects a string from the pipeline input based on a regex match in this case. The regex text is passed to the -pattern parameter.


  • "(?<=CN=).*?(?=,OU=|,DC=)" is the regex (regular expression).


    • (?<=CN=): (?<=) is a positive lookbehind mechanism that looks for the string CN= behind the current position in the match.


    • .*? matches as few as possible characters (.) except newline characters


    • (?=,OU=|,DC=) uses the positive lookahead mechanism ((?=)) to find string ,OU= or (|) the string ,DC=.



  • .Matches is the Matches property of the Select-String output. It contains other properties that are useful for specifying regex capture groups or select from multiple matches. One such property is value, which contains the actual string match.

  • The lookahead and lookbehind mechanisms do not capture any matches. They are merely positional to control where you are in the match sequence.





share|improve this answer

























  • It does seem to be the member output, its spitting out the cn and stuff. I wonder if I tell it instead to pull the exchange name, instead of AD member, it might just spit out the name? In your example, does the cn and ou/dc inside ( ) make it not ouput it?

    – Tekwhat
    Mar 26 at 17:10











  • I am outputting everything between CN= and ,OU. For example, CN=Group Name,OU=OrgUnit,DC=domain would output Group Name. Is that what you are going for? I can add explanation if this output is your desired output.

    – AdminOfThings
    Mar 26 at 17:11












  • That is indeed the desired output. If its not too much trouble can you give a brief explanation of what that's doing? I am still a powershell, well programming for that matter, baby.

    – Tekwhat
    Mar 26 at 17:59











  • I added some explanation. I hope this helps and let me know if it is sufficient.

    – AdminOfThings
    Mar 26 at 18:15











  • Thank you for that, I attempted to add the code to my script, but now it doesn't output anything for the member.

    – Tekwhat
    Mar 26 at 19:13















1














I apologize if I am assuming incorrectly, but I believe you are having trouble with the output of the member property. You may use something like the following:



$SearchBase = "OU=$OU,OU=Hosted Exchange Customers,DC=Domain,DC=local"
$ADGroups = Get-ADGroup -Filter * -SearchBase $SearchBase -Properties Member,CN

$Members = @()
foreach ($ADGroup in $ADGroups)
$Members += $ADGroup.Member


One potential effect of the code above is that you will have an duplicate ADGroup names for each member. If that is not intended, then things will need to be changed.



I maintained a majority of your code, so I will explain what I changed:



($_ | Select-String -pattern "(?<=CN=).*?(?=,OU=|,DC=)").matches.value




  • $_ refers to the current pipeline object from $ADGroup.Member


  • Select-String selects a string from the pipeline input based on a regex match in this case. The regex text is passed to the -pattern parameter.


  • "(?<=CN=).*?(?=,OU=|,DC=)" is the regex (regular expression).


    • (?<=CN=): (?<=) is a positive lookbehind mechanism that looks for the string CN= behind the current position in the match.


    • .*? matches as few as possible characters (.) except newline characters


    • (?=,OU=|,DC=) uses the positive lookahead mechanism ((?=)) to find string ,OU= or (|) the string ,DC=.



  • .Matches is the Matches property of the Select-String output. It contains other properties that are useful for specifying regex capture groups or select from multiple matches. One such property is value, which contains the actual string match.

  • The lookahead and lookbehind mechanisms do not capture any matches. They are merely positional to control where you are in the match sequence.





share|improve this answer

























  • It does seem to be the member output, its spitting out the cn and stuff. I wonder if I tell it instead to pull the exchange name, instead of AD member, it might just spit out the name? In your example, does the cn and ou/dc inside ( ) make it not ouput it?

    – Tekwhat
    Mar 26 at 17:10











  • I am outputting everything between CN= and ,OU. For example, CN=Group Name,OU=OrgUnit,DC=domain would output Group Name. Is that what you are going for? I can add explanation if this output is your desired output.

    – AdminOfThings
    Mar 26 at 17:11












  • That is indeed the desired output. If its not too much trouble can you give a brief explanation of what that's doing? I am still a powershell, well programming for that matter, baby.

    – Tekwhat
    Mar 26 at 17:59











  • I added some explanation. I hope this helps and let me know if it is sufficient.

    – AdminOfThings
    Mar 26 at 18:15











  • Thank you for that, I attempted to add the code to my script, but now it doesn't output anything for the member.

    – Tekwhat
    Mar 26 at 19:13













1












1








1







I apologize if I am assuming incorrectly, but I believe you are having trouble with the output of the member property. You may use something like the following:



$SearchBase = "OU=$OU,OU=Hosted Exchange Customers,DC=Domain,DC=local"
$ADGroups = Get-ADGroup -Filter * -SearchBase $SearchBase -Properties Member,CN

$Members = @()
foreach ($ADGroup in $ADGroups)
$Members += $ADGroup.Member


One potential effect of the code above is that you will have an duplicate ADGroup names for each member. If that is not intended, then things will need to be changed.



I maintained a majority of your code, so I will explain what I changed:



($_ | Select-String -pattern "(?<=CN=).*?(?=,OU=|,DC=)").matches.value




  • $_ refers to the current pipeline object from $ADGroup.Member


  • Select-String selects a string from the pipeline input based on a regex match in this case. The regex text is passed to the -pattern parameter.


  • "(?<=CN=).*?(?=,OU=|,DC=)" is the regex (regular expression).


    • (?<=CN=): (?<=) is a positive lookbehind mechanism that looks for the string CN= behind the current position in the match.


    • .*? matches as few as possible characters (.) except newline characters


    • (?=,OU=|,DC=) uses the positive lookahead mechanism ((?=)) to find string ,OU= or (|) the string ,DC=.



  • .Matches is the Matches property of the Select-String output. It contains other properties that are useful for specifying regex capture groups or select from multiple matches. One such property is value, which contains the actual string match.

  • The lookahead and lookbehind mechanisms do not capture any matches. They are merely positional to control where you are in the match sequence.





share|improve this answer















I apologize if I am assuming incorrectly, but I believe you are having trouble with the output of the member property. You may use something like the following:



$SearchBase = "OU=$OU,OU=Hosted Exchange Customers,DC=Domain,DC=local"
$ADGroups = Get-ADGroup -Filter * -SearchBase $SearchBase -Properties Member,CN

$Members = @()
foreach ($ADGroup in $ADGroups)
$Members += $ADGroup.Member


One potential effect of the code above is that you will have an duplicate ADGroup names for each member. If that is not intended, then things will need to be changed.



I maintained a majority of your code, so I will explain what I changed:



($_ | Select-String -pattern "(?<=CN=).*?(?=,OU=|,DC=)").matches.value




  • $_ refers to the current pipeline object from $ADGroup.Member


  • Select-String selects a string from the pipeline input based on a regex match in this case. The regex text is passed to the -pattern parameter.


  • "(?<=CN=).*?(?=,OU=|,DC=)" is the regex (regular expression).


    • (?<=CN=): (?<=) is a positive lookbehind mechanism that looks for the string CN= behind the current position in the match.


    • .*? matches as few as possible characters (.) except newline characters


    • (?=,OU=|,DC=) uses the positive lookahead mechanism ((?=)) to find string ,OU= or (|) the string ,DC=.



  • .Matches is the Matches property of the Select-String output. It contains other properties that are useful for specifying regex capture groups or select from multiple matches. One such property is value, which contains the actual string match.

  • The lookahead and lookbehind mechanisms do not capture any matches. They are merely positional to control where you are in the match sequence.






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 26 at 19:27

























answered Mar 26 at 17:06









AdminOfThingsAdminOfThings

5,6952 gold badges2 silver badges14 bronze badges




5,6952 gold badges2 silver badges14 bronze badges












  • It does seem to be the member output, its spitting out the cn and stuff. I wonder if I tell it instead to pull the exchange name, instead of AD member, it might just spit out the name? In your example, does the cn and ou/dc inside ( ) make it not ouput it?

    – Tekwhat
    Mar 26 at 17:10











  • I am outputting everything between CN= and ,OU. For example, CN=Group Name,OU=OrgUnit,DC=domain would output Group Name. Is that what you are going for? I can add explanation if this output is your desired output.

    – AdminOfThings
    Mar 26 at 17:11












  • That is indeed the desired output. If its not too much trouble can you give a brief explanation of what that's doing? I am still a powershell, well programming for that matter, baby.

    – Tekwhat
    Mar 26 at 17:59











  • I added some explanation. I hope this helps and let me know if it is sufficient.

    – AdminOfThings
    Mar 26 at 18:15











  • Thank you for that, I attempted to add the code to my script, but now it doesn't output anything for the member.

    – Tekwhat
    Mar 26 at 19:13

















  • It does seem to be the member output, its spitting out the cn and stuff. I wonder if I tell it instead to pull the exchange name, instead of AD member, it might just spit out the name? In your example, does the cn and ou/dc inside ( ) make it not ouput it?

    – Tekwhat
    Mar 26 at 17:10











  • I am outputting everything between CN= and ,OU. For example, CN=Group Name,OU=OrgUnit,DC=domain would output Group Name. Is that what you are going for? I can add explanation if this output is your desired output.

    – AdminOfThings
    Mar 26 at 17:11












  • That is indeed the desired output. If its not too much trouble can you give a brief explanation of what that's doing? I am still a powershell, well programming for that matter, baby.

    – Tekwhat
    Mar 26 at 17:59











  • I added some explanation. I hope this helps and let me know if it is sufficient.

    – AdminOfThings
    Mar 26 at 18:15











  • Thank you for that, I attempted to add the code to my script, but now it doesn't output anything for the member.

    – Tekwhat
    Mar 26 at 19:13
















It does seem to be the member output, its spitting out the cn and stuff. I wonder if I tell it instead to pull the exchange name, instead of AD member, it might just spit out the name? In your example, does the cn and ou/dc inside ( ) make it not ouput it?

– Tekwhat
Mar 26 at 17:10





It does seem to be the member output, its spitting out the cn and stuff. I wonder if I tell it instead to pull the exchange name, instead of AD member, it might just spit out the name? In your example, does the cn and ou/dc inside ( ) make it not ouput it?

– Tekwhat
Mar 26 at 17:10













I am outputting everything between CN= and ,OU. For example, CN=Group Name,OU=OrgUnit,DC=domain would output Group Name. Is that what you are going for? I can add explanation if this output is your desired output.

– AdminOfThings
Mar 26 at 17:11






I am outputting everything between CN= and ,OU. For example, CN=Group Name,OU=OrgUnit,DC=domain would output Group Name. Is that what you are going for? I can add explanation if this output is your desired output.

– AdminOfThings
Mar 26 at 17:11














That is indeed the desired output. If its not too much trouble can you give a brief explanation of what that's doing? I am still a powershell, well programming for that matter, baby.

– Tekwhat
Mar 26 at 17:59





That is indeed the desired output. If its not too much trouble can you give a brief explanation of what that's doing? I am still a powershell, well programming for that matter, baby.

– Tekwhat
Mar 26 at 17:59













I added some explanation. I hope this helps and let me know if it is sufficient.

– AdminOfThings
Mar 26 at 18:15





I added some explanation. I hope this helps and let me know if it is sufficient.

– AdminOfThings
Mar 26 at 18:15













Thank you for that, I attempted to add the code to my script, but now it doesn't output anything for the member.

– Tekwhat
Mar 26 at 19:13





Thank you for that, I attempted to add the code to my script, but now it doesn't output anything for the member.

– Tekwhat
Mar 26 at 19:13













1














It seems like you are over engineering this, based on your end goal. Correct me if I am wrong. Yet, in looking at your code, and your end goal, this would be my take on it.



No need for Write-Host (except for the color stuff) just to send to the screen (Write-Output) is the default, so you don't specifically have to write that out either, but that's a style choice.



"Create OU based Group Memberships Report"

$fLocation = 'C:Temp'

# no need to do this as modules are auto imported since v3, but it does not hurt to have it here
# Import-Module -Name ActiveDirectory

# Use a GUI to provide an OU list to select from.
$OUName = Get-ADOrganizationalUnit -Filter '*' |
Select-Object -Property Name, DistinguishedName |
Out-GridView -Title 'Select the OU name to search' -PassThru

# Set a file name to use. 'spaces in files names are just bad', so remove them
$fName = "$(($OUName).Name)_OU_ADGroup_Membership.csv" -replace ' '

# Remove any report of the same name
If(Test-Path -Path "$fLocation$fName")

Write-Warning -Message "A previous version of the report file is in the destination folder. Removing the file!"
Remove-Item -Path "$fLocation$fName" -Force


# Collect OU, AD group and user data and create a new CSV file
Get-ADOrganizationalUnit -Identity $OUName.DistinguishedName |
ForEach
ForEach
$ADGroup = $PSItem.Name
Get-ADGroupMember -Identity $ADGroup


Write-Host "Your new report file is licated here: $fLocation$fName" -ForegroundColor Yellow
Import-Csv -Path "$fLocation$fName"

#Results

WARNING: A previous version of the report file is in the destination folder. Removing the file!
Your new report file is licated here: C:TempLabUsers_OU_ADGroup_Membership.csv

GroupName Name SamAccountName
--------- ---- --------------
...
TestUsers Test User001 testuser001
...





share|improve this answer

























  • I attempted to run this, and it comes back with "group.name is not found in DC=domain, OU=local" I tried changing it to -SeachBase 'SubOuHere' which gives me the drilled down list to select from, but im not sure why its throwing the above error with and without the -SearchBase added.

    – Tekwhat
    Mar 27 at 16:31















1














It seems like you are over engineering this, based on your end goal. Correct me if I am wrong. Yet, in looking at your code, and your end goal, this would be my take on it.



No need for Write-Host (except for the color stuff) just to send to the screen (Write-Output) is the default, so you don't specifically have to write that out either, but that's a style choice.



"Create OU based Group Memberships Report"

$fLocation = 'C:Temp'

# no need to do this as modules are auto imported since v3, but it does not hurt to have it here
# Import-Module -Name ActiveDirectory

# Use a GUI to provide an OU list to select from.
$OUName = Get-ADOrganizationalUnit -Filter '*' |
Select-Object -Property Name, DistinguishedName |
Out-GridView -Title 'Select the OU name to search' -PassThru

# Set a file name to use. 'spaces in files names are just bad', so remove them
$fName = "$(($OUName).Name)_OU_ADGroup_Membership.csv" -replace ' '

# Remove any report of the same name
If(Test-Path -Path "$fLocation$fName")

Write-Warning -Message "A previous version of the report file is in the destination folder. Removing the file!"
Remove-Item -Path "$fLocation$fName" -Force


# Collect OU, AD group and user data and create a new CSV file
Get-ADOrganizationalUnit -Identity $OUName.DistinguishedName |
ForEach
ForEach
$ADGroup = $PSItem.Name
Get-ADGroupMember -Identity $ADGroup


Write-Host "Your new report file is licated here: $fLocation$fName" -ForegroundColor Yellow
Import-Csv -Path "$fLocation$fName"

#Results

WARNING: A previous version of the report file is in the destination folder. Removing the file!
Your new report file is licated here: C:TempLabUsers_OU_ADGroup_Membership.csv

GroupName Name SamAccountName
--------- ---- --------------
...
TestUsers Test User001 testuser001
...





share|improve this answer

























  • I attempted to run this, and it comes back with "group.name is not found in DC=domain, OU=local" I tried changing it to -SeachBase 'SubOuHere' which gives me the drilled down list to select from, but im not sure why its throwing the above error with and without the -SearchBase added.

    – Tekwhat
    Mar 27 at 16:31













1












1








1







It seems like you are over engineering this, based on your end goal. Correct me if I am wrong. Yet, in looking at your code, and your end goal, this would be my take on it.



No need for Write-Host (except for the color stuff) just to send to the screen (Write-Output) is the default, so you don't specifically have to write that out either, but that's a style choice.



"Create OU based Group Memberships Report"

$fLocation = 'C:Temp'

# no need to do this as modules are auto imported since v3, but it does not hurt to have it here
# Import-Module -Name ActiveDirectory

# Use a GUI to provide an OU list to select from.
$OUName = Get-ADOrganizationalUnit -Filter '*' |
Select-Object -Property Name, DistinguishedName |
Out-GridView -Title 'Select the OU name to search' -PassThru

# Set a file name to use. 'spaces in files names are just bad', so remove them
$fName = "$(($OUName).Name)_OU_ADGroup_Membership.csv" -replace ' '

# Remove any report of the same name
If(Test-Path -Path "$fLocation$fName")

Write-Warning -Message "A previous version of the report file is in the destination folder. Removing the file!"
Remove-Item -Path "$fLocation$fName" -Force


# Collect OU, AD group and user data and create a new CSV file
Get-ADOrganizationalUnit -Identity $OUName.DistinguishedName |
ForEach
ForEach
$ADGroup = $PSItem.Name
Get-ADGroupMember -Identity $ADGroup


Write-Host "Your new report file is licated here: $fLocation$fName" -ForegroundColor Yellow
Import-Csv -Path "$fLocation$fName"

#Results

WARNING: A previous version of the report file is in the destination folder. Removing the file!
Your new report file is licated here: C:TempLabUsers_OU_ADGroup_Membership.csv

GroupName Name SamAccountName
--------- ---- --------------
...
TestUsers Test User001 testuser001
...





share|improve this answer















It seems like you are over engineering this, based on your end goal. Correct me if I am wrong. Yet, in looking at your code, and your end goal, this would be my take on it.



No need for Write-Host (except for the color stuff) just to send to the screen (Write-Output) is the default, so you don't specifically have to write that out either, but that's a style choice.



"Create OU based Group Memberships Report"

$fLocation = 'C:Temp'

# no need to do this as modules are auto imported since v3, but it does not hurt to have it here
# Import-Module -Name ActiveDirectory

# Use a GUI to provide an OU list to select from.
$OUName = Get-ADOrganizationalUnit -Filter '*' |
Select-Object -Property Name, DistinguishedName |
Out-GridView -Title 'Select the OU name to search' -PassThru

# Set a file name to use. 'spaces in files names are just bad', so remove them
$fName = "$(($OUName).Name)_OU_ADGroup_Membership.csv" -replace ' '

# Remove any report of the same name
If(Test-Path -Path "$fLocation$fName")

Write-Warning -Message "A previous version of the report file is in the destination folder. Removing the file!"
Remove-Item -Path "$fLocation$fName" -Force


# Collect OU, AD group and user data and create a new CSV file
Get-ADOrganizationalUnit -Identity $OUName.DistinguishedName |
ForEach
ForEach
$ADGroup = $PSItem.Name
Get-ADGroupMember -Identity $ADGroup


Write-Host "Your new report file is licated here: $fLocation$fName" -ForegroundColor Yellow
Import-Csv -Path "$fLocation$fName"

#Results

WARNING: A previous version of the report file is in the destination folder. Removing the file!
Your new report file is licated here: C:TempLabUsers_OU_ADGroup_Membership.csv

GroupName Name SamAccountName
--------- ---- --------------
...
TestUsers Test User001 testuser001
...






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 27 at 17:00

























answered Mar 27 at 0:14









postanotepostanote

4,9982 gold badges4 silver badges11 bronze badges




4,9982 gold badges4 silver badges11 bronze badges












  • I attempted to run this, and it comes back with "group.name is not found in DC=domain, OU=local" I tried changing it to -SeachBase 'SubOuHere' which gives me the drilled down list to select from, but im not sure why its throwing the above error with and without the -SearchBase added.

    – Tekwhat
    Mar 27 at 16:31

















  • I attempted to run this, and it comes back with "group.name is not found in DC=domain, OU=local" I tried changing it to -SeachBase 'SubOuHere' which gives me the drilled down list to select from, but im not sure why its throwing the above error with and without the -SearchBase added.

    – Tekwhat
    Mar 27 at 16:31
















I attempted to run this, and it comes back with "group.name is not found in DC=domain, OU=local" I tried changing it to -SeachBase 'SubOuHere' which gives me the drilled down list to select from, but im not sure why its throwing the above error with and without the -SearchBase added.

– Tekwhat
Mar 27 at 16:31





I attempted to run this, and it comes back with "group.name is not found in DC=domain, OU=local" I tried changing it to -SeachBase 'SubOuHere' which gives me the drilled down list to select from, but im not sure why its throwing the above error with and without the -SearchBase added.

– Tekwhat
Mar 27 at 16:31

















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%2f55360669%2fcleaner-way-to-export-names%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

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript