Issues exporting powershell to CSV - powershell

It has been many moons since I have last done this and I am having problems exporting some commands to CSV. The biggest one that is getting me right now is
$ADGroupList = Get-ADGroup -Filter * -property * | Select Name -ExpandProperty Name | Sort
ForEach($Group in $ADGroupList)
{
Write-Host "Group: "$Group.Name
Get-ADGroupMember -Identity $Group | Select Name -ExpandProperty Name | Sort
Write-Host ""
}
Export-Csv -path "c:\Temp\test675.csv"
Works fine with out trying to export but the second I try to export the command will run and either generate a blank file or no file at all.
I am able to run other commands with out a issue exporting them to csv. Thanks for any help in advance.

Tim,
From what I can see you're not giving Export-Csv anything to write. Try this:
$ADGroupList = Get-ADGroup -Filter * -property * | Select Name -ExpandProperty Name | Sort
ForEach($Group in $ADGroupList)
{
Write-Host "Group: "$Group.Name
Get-ADGroupMember -Identity $Group |
Select Name -ExpandProperty Name |
Sort |
Export-Csv -path "c:\Temp\test675.csv"
Write-Host ""
}
I'd test this but I don't have access to ActiveDirectory.
Also the Write-Hosts you probably don't want in the .csv file as they won't play well with the format, headers & columns.
HTH

Related

Powershell script : read and insert value from txt file (on 30+ entry)

Sorry, i'm noob for powershell, but want to automate the following:
Got a powershell script:
import-module ActiveDirectory
$username = Read-Host 'Please enter Username!'
Get-ADPrincipalGroupMembership $username | Get-ADGroup -Properties * | select name, description
When run script i enter the username and it give me a list which group the user is member of.
I had a big 50-100 list user list which obtained with Get-aduser -filter * -properties Name | select-object Name | out-file -filepath .\userlist.txt command and saved to a text file.
Is there any way to read every user 1 by 1 and auto fill the username field, then save the output to a text file? when finished with the 1st, script rerun and read the next value.
Is that possible?
Thank you
Here's a few snippets to help you put together what you need.
Get all users from a file containing only usernames
[string[]]$allUsers = Get-Content -Path '.\FileWithUsernames.txt'
Get all active users from AD
[string[]]$allUsers = Get-AdUser -Filter "enabled -eq 'True'" | Select-Object -ExpandProperty 'SAMAccountName'
Loop through users getting the users' group info / doing something with it
foreach ($user in $allUsers) {
Get-AdUser -Identity $user -Properties 'memberof' |
Select-Object -ExpandProperty 'memberof' |
ForEach-Object {
([PSCustomObject]#{ Username=$user; GroupDN = $_})
} |
Export-Csv -Path '.\AllActiveUsersGroups.csv' -Append -Delimiter ',' -Encoding 'Utf8' #-NoTypeInformation #only include the -notypeinfomrmation parameter if using PS rather than PWSH)
}

look up user in AD using text file and export to CSV

Trying to look up a user by DisplayName from a txt file and trying to export it to a CSV.
The expected goal is to have a list of LastName, FirstName (displaynames.txt), have it return an exported CSV file with the information in the "Format-Table" within the code.
Here's the code I've tried
ForEach ($DN in (Get-Content -Path c:\displaynames.txt))
{ Get-ADUser -Filter { displayName -like "*$DN*" } -SearchBase "DC=DOMAIN,DC=NET" | Format-Table Surname,GivenName,SamAccountName,UserPrincipalName | Out-File C:\UserAD.csv
}
the file returns blank. Thoughts? much appreciated in advance
Give this a try, as Jonathan mentioned in his comment, Format-Table is meant to display formatted information to the console and, even though you can use it to export the formatted information to a file it will definitely not be a CSV.
The other potential problem on your code, is that C:\UserAD.csv is getting replaced on each iteration of the loop because Out-File doesn't have the -Append switch.
Get-Content -Path c:\displaynames.txt | ForEach-Object {
if(-not [string]::IsNullOrWhiteSpace($_))
{
Get-ADUser -LDAPFilter "(displayName=*$_*)" -SearchBase "DC=NWIE,DC=NET"
}
} | Select-Object Surname, GivenName, SamAccountName, UserPrincipalName |
Export-Csv path/to/csv.csv -NoTypeInformation

Filter enabled AD users from CSV file

I have a script to import a list of users and want to check if any of these users are disabled. I did try to run the script below but it doesn't filter the users in the CSV file it filters everyone in the entire organization. any suggestions would be appreciated. displayname and SIP address in one of the headers in the CSV file if needed to use the header.
Import-CSV -Path .\Piscataway-+1732.csv | ForEach-Object {
Get-ADUser -Filter "Enabled -eq '$true'" | select Enabled,EmailAddress,SamAccountName
} | Export-CSV .\results77.csv -NoTypeInformation
You have several issues:
You are piping From Import-Csv to ForEach-Object. So Get-ADUser doesn't really know you are piping it input objects.
Get-ADUser's -Identity parameter is by value, not by property name. so you need to echo the appropriate column to send it down the pipe.
If you pipe and use the -Filter parameter the filter is going to apply to the whole domain. It's not going to limit the filter to what you piped in.
If you want the email address to be output you have to tell Get-ADUser to retrieve it.
Try something like this:
Import-CSV -Path .\Piscataway-+1732.csv |
ForEach-Object{ $_.samAccountName }
Get-ADUser -Properties mail |
Where-Object{ $_.Enabled }
Select-Object Enabled,mail,SamAccountName |
Export-CSV .\results77.csv -NoTypeInformation
Note: The Property for the email address is "mail".
Note: Since we don't have a sample of the CSV file the above example
assumes there's a column names samAccountName.
Now, if you want the output to come from the CSV file but validate it according to the user's status in AD we have to change the approach. As always there are several ways to do this.
Example 1:
Import-CSV -Path "c:\temp\test.csv" |
Select-Object #{Label = 'Enabled'; Expression = { ( Get-ADUser $_.samAccountName ).Enabled } },EmailAddress,samAccountName |
Export-CSV -Path "c:\temp\Output.csv" -NoTypeInformation
This again assumes the column name (samAccountName). It also assumes there is not already an "enabled" column. So we are adding a property called enabled that we're getting via Get-ADUser. Then finally re-exporting to Csv.
Example 2:
$CsvData = Import-CSV -Path "c:\temp\test.csv"
$EnabledUsers =
(
$CsvData |
ForEach-Object{ $_.samAccountName } |
Get-ADUser |
Where-Object{ $_.Enabled }
).samAccountName
$CsvData |
Where-Object{ $EnabledUsers -contains $_.samAccountName } |
Select-Object #{Label = 'Enabled'; Expression = { $true } },EmailAddress,samAccountName |
Export-Csv -Path "c:\temp\Output.csv" -NoTypeInformation
Example 1 is great for small jobs but too many individual calls to Get-ADUser might be slow for larger runs. In this example Import the CSV data once. Then use it to get a flat list of those entries that are enabled in AD. Once you have that you can use the -contains operator to check if the account is enabled. Once again there's a little extra work to add the "Enabled" property.
This should give you a general idea. There are probably a dozen more ways to do this, but hopefully this give you a good idea of what has to happen. Let me know if this helps.

Passing results to a -like filter in PowerShell

I am trying to create a script to take care of a repetitive task I have. Basically I need to get the person's ID that manages a particular folder.
My first script tells me the various security groups assigned to a specified folder. The second script takes a specified AD group and tells me who manages it. Ideally I want to just run the script, input my folder name and have it tell me who manages the various AD groups assigned. I can then go and do the rest. But I am having an issue with the output of the first script. I have it so it displays in the console correctly, but I cannot figure out how to get those results into the filter in the second script.
Script one:
$FN = Read-Host -Prompt "Please enter Folder name"
$ADG = (Get-Acl $FN).Access |
Select IdentityReference |
Where-Object IdentityReference -like '*SL*'
foreach ($ACL in $ADG) {
$Group.Fullname + ($ACL.IdentityReference.Value.Split('\'))[1] | Out-String
}
Script two:
Get-ADGroup -Filter {Name -like "use output here"} -Properties managedby |
Select managedby
I would be most appreciative of any assistance. ESPECIALLY if I am barking up the wrong PowerShell command! My first foray into using multiple queries in a script.
It's not quite clear to me what the $Group.Fullname + (...)[1] | Out-String is supposed to do, but assuming that you want to run the second command for each identity reference from your first command you could do something like this:
Get-Acl $FN |
Select-Object -Expand Access |
Select-Object -Expand IdentityReference |
Where-Object { $_.Value -like '*SL*' } |
ForEach-Object {
$name = $_.Value.Split('\', 2)[-1]
Get-ADGroup -Filter "Name -like '*${name}*'" -Property ManagedBy
} |
Select-Object -Expand ManagedBy |
Get-ADUser

Get PowerShell to search extension attribute in AD

I'm trying to get PowerShell to import a CSV file that has a list of employee ID numbers and search AD for those numbers. If I run it the way it is now I get no results, I just get a blank CSV files it creates at the end of the process.
If I tell PowerShell to Write-Host $.ID it will give me a list of all the IDs that are in the imported CSV. So it seems that it's able to read the file just fine. I have also tested and if I replace Get-ADUser -Filter "extensionAttribute13 -like '$.ID'" with an actual ID number instead of $_.ID I get the result I'm looking for.
I'm not 100% sure what I'm missing in getting the employee numbers passed along to return the data I need.
Import-Csv C:\temp\emplid.csv |
ForEach {
Get-ADUser -Filter "extensionAttribute13 -like '$_.ID'" -Server "dc01" -Properties * | select extensionAttribute13, Name, Description
} | Export-Csv C:\temp\employees.csv -NoTypeInformation
Any help would be extremely appreciated.
Thank you!
You need to put a subexpression $() around $_.ID:
Import-Csv C:\temp\emplid.csv |
ForEach {
Get-ADUser -Filter "extensionAttribute13 -like '$($_.ID)'" -Server "dc01" -Properties * | select extensionAttribute13, Name, Description
} | Export-Csv C:\temp\employees.csv -NoTypeInformation