How to export csv table in Powershell? - powershell

I try to export .csv table using Powershell but in table i see only 1 field with incorrect value
$Users=Get-ADUser -Filter * -Properties *
$PCs = Get-ADComputer -Filter * -Properties name, ManagedBy
foreach ($user in $Users)
{
foreach ($pc in $PCs)
{
if ($user.DistinguishedName -eq $pc.ManagedBy)
{
Select-Object $user.Name, $pc.Name | Export-Csv -Path 'D:\123.csv' -Delimiter ";" -Encoding UTF8 -Append
}
}
}
But if i use this, its work.
$Users=Get-ADUser -Filter * -Properties *
$PCs = Get-ADComputer -Filter * -Properties name, ManagedBy
$text =#()
foreach ($user in $Users)
{
foreach ($pc in $PCs)
{
if ($user.DistinguishedName -eq $pc.ManagedBy)
{
$text_new = $user.Name + ";" +$user.Department+";"+$user.Company+ ";"+ $pc.Name #| Export-Csv -Path 'D:\123.csv' -Delimiter ";" -Encoding UTF8 -Append
$text = $text + $text_new
}
}
}
$text > D:\123.csv
I don't understant why don't work with Select-Object. Can anybody explain me why?

Select-Object is used to select properties of an object, i.e. after a pipeline. This should do the trick
[pscustomobject]#{Name = $user.Name; PC = $pc.Name} | Export-Csv...
See MS Docs for more info
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-object?view=powershell-7.1

Related

Getting canonical name for each members of the users via powershell

I want to get canonical name for each groups as well. how can I do that ?
Here is my script :
Get-ADUser -Filter {Enabled -eq $true} -Properties * | Select displayname ,#{Name="MemberOf";Expression={($_.MemberOf | %{(Get-ADGroup $_).sAMAccountName}) -Join ";"}} | Export-Csv -Path "c:\temp\users.csv" -NoTypeInformation -Encoding UTF8
My output :
"displayname","MemberOf"
"User01","Group01;Group02;Group03"
My desired output:
"displayname","MemberOf"
"User01","Group01;Contoso.com/OU1/OU2;Group02;Contoso.com/OU21/OU52;Group03;Contoso.com/OU1/OU21/OU22"
I agree with Mathias but this is how you can do it using the code you already have. Definitely recommend you to only call the properties that you need to query.
Get-ADUser -Filter {Enabled -eq $true} -Properties Displayname,MemberOf |
Select-Object Displayname,
#{
Name="MemberOf"
Expression={
# ($_.MemberOf | ForEach-Object{
# (Get-ADGroup $_ -Properties CanonicalName).CanonicalName
# }) -Join ";"
# You can pipe $_.MemberOf to Get-ADGroup, since it's an array of
# distinguishedNames it should work fine
($_.MemberOf | Get-ADGroup -Properties CanonicalName).CanonicalName -Join ";"
}
} | Export-Csv -Path "c:\temp\users.csv" -NoTypeInformation -Encoding UTF8
An alternative to that code, using a more classical approach:
$users = Get-ADUser -Filter {Enabled -eq $true} -Properties DisplayName
$result = foreach($user in $users)
{
$params = #{
LDAPFilter = "(member=$($user.DistinguishedName))"
Properties = "CanonicalName"
}
$membership = (Get-ADGroup #params).CanonicalName -join ";"
[pscustomobject]#{
DisplayName = $user.DisplayName
MemberOf = $membership
}
}
$result | Export-Csv -Path "c:\temp\users.csv" -NoTypeInformation -Encoding UTF8
First of all, you shouldn't be using Properties * when you only need two properties.
Then, the -Filter should be a string, not a scriptblock.
With just a small adaptation to your code, this should work:
Get-ADUser -Filter "Enabled -eq 'True'" -Properties DisplayName, MemberOf |
Select-Object DisplayName,
#{Name = "MemberOf"; Expression = {
($_.MemberOf | ForEach-Object {
($_ | Get-ADGroup -Properties CanonicalName).CanonicalName -Join ";" })
}
} |
Export-Csv -Path "c:\temp\users.csv" -NoTypeInformation -Encoding UTF8
Looking at your latest comment, I believe you want the group NAME joined with the canonicalname of the group as well.
You can do this like so:
Get-ADUser -Filter "Enabled -eq 'True'" -Properties DisplayName, MemberOf |
Select-Object DisplayName,
#{Name = "MemberOf"; Expression = {
$_.MemberOf | ForEach-Object {
$group = $_ | Get-ADGroup -Properties CanonicalName
'{0};{1}' -f $group.Name, ($group.CanonicalName -join ';')
}
}
} |
Export-Csv -Path "c:\temp\users.csv" -NoTypeInformation -Encoding UTF8

Find computers that are not members of a specific GG group

I use a script to export users that are not in specific GG groups in active directory but I want to do the same with computers.
This is the example that works with users:
$groups = 'GG_LCS_UsersType4', 'GG_LCS_UsersType3', 'GG_LCS_UsersType2', 'GG_LCS_SpecialUsers'
$whereFilter = $groups | Foreach-Object {
$g = (Get-ADGroup -server $domain $_).DistinguishedName
"{0} '{1}'" -f '$_.memberOf -notcontains',$g
}
$whereFilter = [scriptblock]::Create($whereFilter -join " -and ")
$users = (Get-ADUser -server $Domain -filter {objectclass -eq "user"} -properties memberof).where($whereFilter)
$users | Select-Object SamAccountName,Enabled |
Export-Csv "${Domain}_Users_withoutGG.csv" -NoTypeInformation -Encoding UTF8 -Append
And I tried this in order to do the same with computers, but this doesn't work:
$groups = 'GG_LCS_ComputersType2', 'GG_LCS_ComputersType3', 'GG_LCS_ComputersType4'
$whereFilter = $groups | Foreach-Object {
$g = (Get-ADGroup -server $domain $_).DistinguishedName
"{0} '{1}'" -f '$_.memberOf -notcontains',$g
}
$whereFilter = [scriptblock]::Create($whereFilter -join " -and ")
$users = (Get-ADComputer -server $Domain -filter {objectclass -eq "computer"} -properties memberof).where($whereFilter)
$users | Select-Object SamAccountName,Enabled |
Export-Csv "${Domain}_Computers_withoutGG.csv" -NoTypeInformation -Encoding UTF8 -Append
Could you help me? Thanks!
Try adding the -SearchBase
$AD = Get-ADComputer -Filter * -Properties $properties -SearchBase "DC=subdomain,DC=domain,DC=com" -Server $server
$AD | Select-Object * | Export-Csv -NoTypeInformation $filePath -Encoding UTF8

getting some attributes, others missing in query loop

I have a PS script that loops AD to get lastlogon attribute plus others.
I want to get the displayName, SamAccountName, whenCreated, whenChanged, distinguishedname and last logontime.
Now it all works fine except the output CSV is missing the displayName, whenCreated and whenChanged attributes.
I'm puzzeled that it works for some attributes and not others.
Here's my code:
Import-Module ActiveDirectory
function Get-ADUsersLastLogon() {
$dcs = Get-ADDomainController -Filter {Name -like "*"}
$users = Get-ADUser -Filter * -SearchBase "ou=Other Users,ou=Users,ou=Items,dc=mydc,dc=,dc=com"
$time = 0
$exportFilePath = "c:\tmp\lastLogon $(get-date -f dd-MM-yyyy).csv"
$columns = "name;username;whencreated;whenchanged;DNname;datetime"
Out-File -FilePath $exportFilePath -Force -InputObject $columns
foreach ($user in $users) {
foreach ($dc in $dcs) {
$hostname = $dc.HostName
$currentUser = Get-ADUser $user.SamAccountName |
Get-ADObject -Server $hostname -Properties lastLogon
if ($currentUser.LastLogon -gt $time) {
$time = $currentUser.LastLogon
}
}
$dt = [DateTime]::FromFileTime($time)
$row = $user.displayName + ";" + $user.SamAccountName + ";" +
$user.whenCreated + ";" + $user.whenChanged + ";" +
$user.distinguishedName + ";" + $dt
Out-File -FilePath $exportFilePath -Append -NoClobber -InputObject $row
$time = 0
}
}
Get-ADUsersLastLogon

Import a CSV and after that get AD group infos out of one column

I use a CSV file where I find the accumulated security infos of file-server-folders.
CSV looks like that:
Pfad;Ordnerebene;Berechtigungsgruppe_Domaene;Berechtigungsgruppe;Rechteart;Recht
X:\;0;VORDEFINIERT;Administrators;Allowed;CHANGE
X:\;0;company;AdminsEupl;Allowed;CHANGE
X:\;0;company;EUPL.EDV;Allowed;CHANGE
X:\;0;;;Allowed;CHANGE
X:\backup;1;company;AdminsEupl;Allowed;CHANGE
I want to question active directory about details (owner, members, managedby, etc.) from "Berechtigungsgruppe" and export this details into another CSV.
Code is this:
$dateipfad = "<pathtomyfile>"
Import-Csv $dateipfad -Encoding Unicode -Delimiter ";"| foreach {
$a = ($_.Pfad)
$b = ($_.Ordnerebene)
$c = ($_.Berechtigungsgruppe_domaene)
$d = ($_.Berechtigungsgruppe)
$e = ($_.Rechteart)
$f = ($_.Recht)
$g = '*' + $d + '*'
}
$Array = Get-ADGroup -Filter {name -like '$g'} |
Select-Object -Unique -ExpandProperty Name
$Liste = foreach ($element in $Array) {
Get-ADGroup $element -Properties managedby |
Get-ADGroupMember -Identity $element |
Get-Aduser -Properties name, DisplayName, Mail |
Select-Object name, DisplayName, Mail,
#{Name='Group';Expression={$element}}, managedby
}
$Liste
$Liste | Export-Csv -Path o:\powershell\GruppenMitglieder.csv -Append -Encoding Unicode -NoTypeInformation -Delimiter ';'
but all I got in the resulting CSV is: ÿþ. What am I doing wrong?

Powershell - Append Group Name and Members

I am trying to write a script that will create a CSV file with the name of the group and its members. My script fails with the error:
The appended object does not have a property that corresponds to the following column
I am sure it is a simple mistake and I'd bang away at it but I need the data quickly.
$SearchBase = "OU=Groups,DC=domain,DC=local"
$SPGroups = Get-ADGroup -filter * -SearchBase $SearchBase | select name
Foreach ($i in $SPGroups){
#$Members += get-ADGroupMember -Identity $i.name | select name
$i.name | Export-Csv -append -Path c:\bin\membersof.csv
get-ADGroupMember -Identity $i.name | select name | Export-CSV -append -Path c:\bin\membersof.csv
}
Thank You!
Try this:
$SearchBase = "OU=Groups,DC=domain,DC=local"
Get-ADGroup -Filter * -SearchBase $SearchBase | % {
$group = $_.name
Get-ADGroupMember -Identity $group |
select #{n='Group';e={$group}}, #{n='Member';e={$_.Name}}
} | Export-CSV 'C:\bin\membersof.csv'
#Create Custom Data Container
$header = #("Group,Member") #Columns
$temp = #()
$data = #()
$data += $header
$SearchBase = "OU=Groups,DC=domain,DC=local"
Get-ADGroup -filter * -SearchBase $SearchBase | % {
#For Each Group
$Groups = $_.name
get-ADGroupMember -Identity $groups | % {
#For Each Member
$Members = $_.Name
#Add Row
$temp = "$Groups,$Members"
$data += $temp
}
}
#output data to csv
$data | ConvertFrom-Csv | Export-Csv -Path c:\bin\membersof.csv -NoTypeInformation