Import-CSV -Path C:\Users\*******\Desktop\Powershell\Input.csv |
ForEach {
Get-ADComputer -identity $_.computer -properties * |
select CN, extensionAttribute1, created, Description, DistinguishedName, enabled
} |
export-csv -path C:\Users\*******\Desktop\Powershell\Output.csv -Append -Encoding UTF8 -Delimiter ";"
Hi, how i can change my PS script.
If user from CSV not found then paste NAME;"NOT_FOUND", now my script just skip users that were not found with errors.
What you could do is a try/catch block, so that if an error occurs (when it does not exists) it outputs not found for the value "CN".
Import-CSV -Path C:\Users\*******\Desktop\Powershell\Input.csv | ForEach {
$computer = $_.computer
try{
Get-ADComputer -identity $computer -properties *
}catch{
#{
CN = "$computer not found"
}
}
} | select #{n="CN";e={$_.CN}}, extensionAttribute1, created, Description, DistinguishedName, enabled | Export-Csv -path C:\Users\*******\Desktop\Powershell\Output.csv -Append -Encoding UTF8 -Delimiter ";"
Or as your less readable one-liner:
Import-CSV -Path C:\Users\*******\Desktop\Powershell\Input.csv | ForEach {try{Get-ADComputer -identity $_.computer -properties *}catch{#{CN = "Not found"}}} | select #{n="CN";e={$_.CN}}, extensionAttribute1, created, Description, DistinguishedName, enabled | export-csv -path C:\Users\*******\Desktop\Powershell\Output.csv -Append -Encoding UTF8 -Delimiter ";"
Note that at the select we use an expression. It says name (n)="CN";expression (e)=$_.CN which is the CN and in case of an error it consists of the value "not found" from the catch block. You can also choose to add this expression to more/different values of the select statement if you enrich the object at the catch block. Or use if/else in the expression.
Related
I am trying to find out the Active Directory groups all our active users are in and want to export it to a CSV file. However the following command presents garbage in the related CSV file.
This is my code failing:
Import-Module ActiveDirectory
Get-ADUser -SearchBase "CN=Users,DC=Mycompany,DC=de" -Filter * | where { $_.enabled -eq "true" } | foreach-object {
write-host "User:" $_.Name
Get-ADPrincipalGroupMembership $_.SamAccountName | foreach-object {
write-host "Member of:" $_.name | export-csv "C:\scripts\output\ad-user-with-group-memberhip.csv" -NoTypeInformation -Encoding UTF8
}
}
Any idea what am I doing wrong here?
Write-Host only writes text to the console window. It doesn't output anything useful to pipe through to Export-Csv.
Also, unless you add switch -Append, you should set the Export-Csv cmdlet as last line in the code, otherwise you will overwrite it in every iteration.
Try
with Select-Object
Import-Module ActiveDirectory
Get-ADUser -SearchBase "CN=Users,DC=Mycompany,DC=de" -Filter "Enabled -eq $true" |
Select-Object Name, #{Name = 'Groups'; Expression = {($_ | Get-ADPrincipalGroupMembership).Name -join '; '}} |
Export-Csv -Path "C:\scripts\output\ad-user-with-group-memberhip.csv" -NoTypeInformation -Encoding UTF8
or with ForEach-Object
Import-Module ActiveDirectory
$result = Get-ADUser -SearchBase "CN=Users,DC=Mycompany,DC=de" -Filter "Enabled -eq $true" |
ForEach-Object {
[PsCustomObject]#{
Name = $_.Name
Groups = ($_ | Get-ADPrincipalGroupMembership).Name -join '; '
}
}
$result | Export-Csv -Path "C:\scripts\output\ad-user-with-group-memberhip.csv" -NoTypeInformation -Encoding UTF8
I'm executing a Get-ADComputer and trying to iterate through a loop that pulls computer names from individual rooms. I'm trying to output each room to a different Excel sheet.
I'm running PowerShell Version 5:
$results = for($room=102; $room -le 110; $room++) {
Get-ADComputer -SearchBase $oubase -Properties Name, Description -Filter * |
Where-Object {$_.description -clike "*RM $Room"}
}
$results |
Select-Object Name, Description |
Export-CSV '\\Desktop\Room_Hosts.csv' -NoTypeInformation -Encoding UTF8 -Append
What do I need to do to fix the Excel sheet output?
Your post says you want an Excel sheet, but your code is outputting to a CSV. You cannot add a second sheet to a CSV. You can export different CSV files per computer object.
$results = for($room=102; $room -le 110; $room++) {
Get-ADComputer -SearchBase $oubase -Properties Name, Description -Filter * |
Where-Object {$_.description -clike "*RM $Room"}
}
$results |
Select-Object Name, Description | Foreach-Object {
$_ | Export-CSV -Path ("\\Desktop\{0}.csv" -f $_.Name) -NoTypeInformation -Encoding UTF8 -Append
If the problem is getting the domain name, you can add some code to your Select-Object command.
$results = for($room=102; $room -le 110; $room++) {
Get-ADComputer -SearchBase $oubase -Properties Name,Description,DNSHostName -Filter * |
Where-Object {$_.description -clike "*RM $Room"}
}
$results |
Select-Object Name,Description,#{n='Domain';e={$_.DNSHostName -Replace $("{0}." -f $_.Name}} |
Export-CSV '\\Desktop\Room_Hosts.csv' -NoTypeInformation -Encoding UTF8 -Append
Explanation For Retrieving Computer Object's Domain:
The DNSHostName property contains the FQDN of the computer object. So you only need to remove the host name part of that string. Here, we simply replace the hostname and the following . character with nothing. Hostname is retrieved from the Name property of the computer object. The -f operator is used to simply append the . character to the name. The Select-Object uses a hash table to calculate the domain value and store it in a property called Domain.
Alternatively, you can apply the same concepts from above for getting the domain name but use the CanonicalName of the computer object with the -Split operator.
$results = for($room=102; $room -le 110; $room++) {
Get-ADComputer -SearchBase $oubase -Properties Name,CanonicalName,Description -Filter * |
Where-Object {$_.description -clike "*RM $Room"}
}
$results |
Select-Object Name,Description,#{n='Domain';e={($_.CanonicalName -Split "/")[0]}} |
Export-CSV '\\Desktop\Room_Hosts.csv' -NoTypeInformation -Encoding UTF8 -Append
I want to output all hostnames within a network first with a foreach loop, in order (for example) to be able to ping them.
However with the following code I do not get any output in the console. The CSV file will be saved, but what is written in the loop will not be executed.
Does anyone know what the reason for this is and how I can solve it?
Import-Module activedirectory
Get-ADComputer -Filter * -Property * | Select Name | Export-CSV -Path $env:TEMP\ZZZEXPORTE.csv -NoTypeInformation -Encoding UTF8 | ForEach {
$computerName = $_.Name
Write-Host $computerName
Write-Host "----"
}
This occurs because Export-CSV does not output an object. Sometimes cmdlets like this have a -PassThru parameter which you can use to have an object passed along, but thats not the case with Export-CSV, they simply expect it to always be the last cmdlet in the pipeline.
You should instead do this:
$Computers = Get-ADComputer -Filter * -Property * | Select Name
$Computers | Export-CSV -Path $env:TEMP\ZZZEXPORTE.csv -NoTypeInformation -Encoding UTF8
$Computers | ForEach {
$computerName = $_.Name
Write-Host $computerName
Write-Host "----"
}
You could also do this:
Get-ADComputer -Filter * -Property * | Select Name | ForEach {
$computerName = $_.Name
Write-Host $computerName
Write-Host "----"
$_
} | Export-CSV -Path $env:TEMP\ZZZEXPORTE.csv -NoTypeInformation -Encoding UTF8
Noting that we have to add $_ to our ForEach-Object loop so that it outputs the current item to the pipeline, but that our Write-Host statements don't effect the pipeline because they are writing to the console only. To be honest though, this is a bit harder to follow for anyone else reading your code.
I try since a while to create a csv file which contain:
"Group Name","SamAccountName"
Where GroupName is the name of the Group abd SamAccountName is the name of the user which is part of the Group.
I try this:
Get-ADUser -Filter * -Properties DisplayName,memberof | % {
$Name = $_.DisplayName
$_.memberof | Get-ADGroup | Select #{N="User";E={$Name}},Name
} | Export-Csv -NoTypeInformation -Encoding UTF8 -delimiter "," "All_Users_With_All_Their_Groups.csv"
However it doesn't work like I want.
I try to google many example but it's not pretty simple I think as I don't find some relevant example.
Do you have any idea?
This should do your work:
Import-Module ActiveDirectory ;
Get-ADGroup -Filter {name -like "*Your Group Name*"} -Properties Description,info | Select Name,samaccountname | Export-Csv D:\output.csv -NoTypeInformation
Get-ADGroupMember YourGroupName # to list members ;
I've created two ways, dunno which one You wanted
get-aduser -Filter * -Properties memberof |
%{[pscustomobject]`
#{'Groups Names'=$(($_.memberof | Get-ADGroup).name -join "," );
User=$($_.samaccountname)}}|
Export-Csv -NoTypeInformation -Encoding UTF8 -Delimiter ',' "output.csv"
Get-ADGroup -Filter * -Properties members |
%{[pscustomobject]#{'Group'=$($_.name);
'Members'=$(($_.members | Get-ADUser).samaccountname -join ",")}} |
Export-Csv -NoTypeInformation -Encoding UTF8 -Delimiter ',' "output.csv"
I have a PowerShell script below
$ous = 'ou=office,dc=xxx,dc=com',`
'ou=shop0,dc=xxx,dc=com',`
'ou=shop1,dc=xxx,dc=com',`
'ou=shop2,dc=xxx,dc=com'
$outfile = 'c:\work\userinfo.csv'
New-Item -Force -type "file" -Path 'c:\work\userinfo.csv'
$ous | ForEach {
Get-ADUser -Filter * -SearchBase $_ |
Select-Object -Property CN,`
DisplayName,`
GivenName,`
Surname,`
SamAccountName,`
PasswordExpired,`
mail,`
Description,`
Office,`
EmployeeNumber,`
Title |
Sort-Object -Property Name |
export-csv -Append $outfile -NoTypeInformation
}
Then when I run it, I got error message "New-Item: access to the path c:\work\userinfo.csv" is denied.
What's the cause for this error?
Update:
In my case, somehow, PowerShell is case-sensitive....the output folder name is uppercase, in my script is lowercase, it works after I match them.
I am bypassing the reason for the error ( of which I'm not sure of the cause.). Another way to get what you want
each time I run script, I could get an fresh result without previous results
You just need to move the output code outside the loop and remove the append. Pipeline handles the Append for you.
$ous | ForEach {
Get-ADUser -Filter * -SearchBase $_ |
Select-Object -Property CN,`
DisplayName,`
GivenName,`
Surname,`
SamAccountName,`
PasswordExpired,`
mail,`
Description,`
Office,`
EmployeeNumber,`
Title
} | Sort-Object -Property Name |
export-csv -Append $outfile -NoTypeInformation
Noticed something
You are not calling all the properties you are using in your select statement. That should lead to some null columns in your output. I would update your code to something like this.
$props = "CN","DisplayName","GivenName","Surname","SamAccountName","PasswordExpired","mail","Description","Office","EmployeeNumber","Title"
$ous | ForEach-Object {
Get-ADUser -Filter * -SearchBase $_ -Properties $props | Select-Object $props
} | Sort-Object -Property Name |
export-csv $outfile -NoTypeInformation