Filter Get-Mailbox by LegacyExchangeDN - exchangewebservices

I am getting the accounts able to creat meetings in rooms with this:
Get-CalendarProcessing -Identity ARoom | select -ExpandProperty BookInPolicy
This gets me the LegacyExchangeDN of the accounts. But when I try to get the Exchange-mailboxes with the following code, PowerShell starts listing all accounts available.
foreach ($i in $a) {Get-Mailbox -filter {LegacyExchangeDN -like $i}}
Being in a large organisation there is some 20k mailboxes, and it doesn't list the wanted result.
If I use one of the LegacyExchangeDN's in
"/o=ExchangeLabs/..." | Get-Mailbox -Filter {LegacyExchangeDN -like $_}
it gets the mailbox as intended.
So how do I get all the accounts from a rooms BookInPolicy via LegacyExchangeDN?

I found out that filtering is not necessary. You can get the mailaccounts with simply:
Get-Mailbox $i.LegacyExchangeDN
So this code gets everything:
Get-CalendarProcessing -Identity ARoom | select -ExpandProperty BookInPolicy | % {Get-Mailbox $_}

Related

How to get via Powershell AD computer owner attributes like email and account name?

I have a computers that have assigned to users as managedby, I want to get list in JSON format where hostname is a key, and user attributes are values.
But I stuck to get that in one command :/ and put that in json, so use csv for a while.
I run these 2 commands succesfuly:
Get-ADComputer -Filter * -property managedby | select name, managedby > C:\Windows\Temp\computerowners.csv
Get-ADUser -Filter * -SearchBase 'CN=My User,DC=example,DC=com' -Properties SamAccountName | Format-Table -Property Name, samaccountname, userprincipalname -AutoSize
where search base is managedby value from first one.
I expect to have output like that:
hostname, name, samaccountname, userprincipalname
I try to combine above 2 commands like that:
Get-ADComputer -Filter * -property managedby | foreach {get-aduser -Filter * -SearchBase $managedby -Properties name, samaccountname, userprincipalname} | select name, samaccountname, userprincipalname > C:\Windows\Temp\computerowners.csv
but it want work - as not pickup managedby properly as I understand... any help with saving that in json will be more than welcome.
You didn't define the variable $managedby that you use in the ForEach-Object loop, hence the variable is $null. You need to use the property ManagedBy of the current object in the pipeline ($_.ManagedBy).
With that said, you're making the whole thing way more complicated than it needs to be. PowerShell can do a lot of the heavy lifting for you if you allow it to. Get-ADUser can read from the pipeline, so all you need to do is pass the owner's distinguished name. You also don't need to explicitly specify the properties Name, SamAccountName and UserPrincipalName, because Get-ADUser returns them by default. Plus, since you want CSV output anyway, use Export-Csv instead of the redirection operator.
Get-ADComputer -Filter * -Property managedby |
Select-Object -Expand ManagedBy |
Get-ADUser |
Select-Object Name, SamAccountName, UserPrincipalName |
Export-Csv C:\Windows\Temp\computerowners.csv -NoType
To include the computername in the output adjust the above code as follows:
Get-ADComputer -Filter * -Property managedby |
ForEach-Object {
$computer = $_.Name
if ($_.ManagedBy) { Get-ADUser $_.ManagedBy } else { '' }
} |
Select-Object #{n='ComputerName';e={$computer}}, Name, SamAccountName,
UserPrincipalName |
Export-Csv C:\Windows\Temp\computerowners.csv -NoType
To get a datastructure that can be exported to JSON using the computername as the key for the nested user attributes a different approach would be more elegant, though. Collect all relevant user attributes in a hashtable with the computername as the key:
$computers = #{}
Get-ADComputer -Filter * -Property managedby | ForEach-Object {
$computers[$_.Name] = if ($_.ManagedBy) {
Get-ADUser $_.ManagedBy | Select-Object Name, SamAccountName, UserPrincipalName
} else {
New-Object -Type PSObject -Property #{
Name = ''
SamAccountName = ''
UserPrincipalName = ''
}
}
}
Then create an object from that hashtable and convert it to JSON:
New-Object -Type PSObject -Property $computers | ConvertTo-Json
This should get you pretty far:
Get-ADComputer -Filter * -Property ManagedBy,CN | ForEach-Object {
# only query AD if there actually is a manager
if ($_.ManagedBy) {
$manager = $_.ManagedBy | Get-ADUser
} else {
$manager = $null
}
# return a custom object with 4 properties
[pscustomobject]#{
hostname = $_.CN
name = $manager.Name
samaccountname = $manager.SamAccountName
userprincipalname = $manager.UserPrincipalName
}
}
Note: Any value created in a script block and not explicitly captured in a variable or explicitly discarded via Out-Null automatically becomes a return value of that block. In this case, the ForEach-Object body will emit a series of PSCustomObject instances.
Use the result in any way you like, for example format it as JSON or CSV.
Related reading
How do I return a custom object in Powershell that's formatted as a table?
Jonathan Medd's Blog: PowerShell v3 – Creating Objects With [pscustomobject]

PowerShell Get-ADUser - Tally of attributes

I am looking at a way to list how many times an AD property matching a certain value appears against each user.
Specifically - Users in our AD have a Custom Attribute distinguishing their company. I need to run monthly reports that will display a list of all companies and how many users are listed.
This is as close as I have it - but it is not user friendly for our Accounts team.
import-csv c:\HostedCompanyList.csv -header ID |
foreach {
$total = (get-aduser -filter "(extensionattribute1 -eq '$($_.ID)') -and (extensionattribute2 -eq 'billed')" -properties *).count
write-host $total $_.ID
}
This is the content of HostedCompanyList.csv
ID
Company1
Company2
Company3
My output shows as `
35 Company1
12 Company2
27 Company3
I'd like to output this information to a CSV or HTML file as opposed to displaying it on the PS window.
I appreciate this is likely already a very long winded way of running this query - could I perhaps have overlooked a much simpler method?
Bonus points if there's a way I can do this without having to import a CSV file at all - that would cut out the need to add additional entries into that list when new "companies" get added on or taken away!
Thank you for any help offered.
Untested, since I don't have the same extension attributes, but this shape:
query everyone, filter the billed people
group-object by company name
select properties and export to csv
should work with one query, no text file to read from, and csv export.
$filter = "extensionattribute2 -eq 'billed'"
$users = Get-ADUser -filter $filter -Property extensionattribute1, extensionattribute2
$groups = $users | Group -Property extensionattribute1
$groups | select Count, Name | Export-Csv out.csv -notypeinformation

script to output event logs not accessing not working

I am new to powershell, Need to write a script to pull security logs and then place the data in a time stamped csv file in a location but I am getting I get stuck in a loop. My desired outcome is a CSV file in my directory with the security logs and time stamp for file name here is what I got for the part it is flagging.
Get-EventLog "Security" -After $Date `
| Where -FilterScript {$_.EventID -eq 4624 -and $_.ReplacementStrings[4].Length -gt 10 -and $_.ReplacementStrings[5] -notlike "*$"} `
| foreach-Object {
$row = "" | Select UserName, LoginTime
$row.UserName = $_.ReplacementStrings[5]
$row.LoginTime = $_.TimeGenerated
$eventList += $row
$variable | Export-Csv c:\output.csv
}
$eventList
Export-Csv : Cannot bind argument to parameter 'InputObject' because it is null.
At line:12 char:21
I am guessing the issue is here? Again my apologize very little scripting background, just trying to make a process better.
$variable | Export-Csv c:\output.csv
Yes, you don't define $variable within your script, that is why you getting this exception. It looks like you trying to export a bunch of EventLog entries as csv, so the Export-Csv cmdlet probably should belong outside the Foreach-Objectcmdlet. Maybe you want to do something like this:
Get-EventLog "Security" -After $Date `
| Where -FilterScript {$_.EventID -eq 4624 -and $_.ReplacementStrings[4].Length -gt 10 -and $_.ReplacementStrings[5] -notlike "*$"} `
| foreach-Object {
$row = "" | Select UserName, LoginTime
$row.UserName = $_.ReplacementStrings[5]
$row.LoginTime = $_.TimeGenerated
$row # this will put the current row to the pipeline
} | Export-Csv 'c:\output.csv'

Exporting all memberof values using Export-Csv with join

I'm trying to pump out a list of users in a specific OU along with their group memberships to a CSV. I wanted a list of groups but I get "Microsoft.ActiveDirectory.Management.ADPropertyValueCollection" My command is
Get-ADUser -Filter * -SearchBase "ou=Vendor Accounts,dc=mydomain,dc=com" -Properties * | Select ‘Name’,’DisplayName’,’SamAccountName’, #{Name=’MemberOf';Expression={[string]::join(“;”, ($_.MemberOf))}}| export-csv c:\temp\citrix_vendors.csv -NoTypeInformation -Append
I get all the other properties as expected, pretty columns and everything, but can't seem to get the multi-valued attribute to output the way I want. I'm running v4.
I looked at How to list AD group membership for AD users using input list? and tried implementing a similar fix,
$GroupMembership = ($user.memberof | % { (Get-ADGroup $_).Name; }) -join ';';
$user = Get-ADUser -Filter * -SearchBase "ou=Vendor Accounts,dc=mydomain,dc=com" -Properties *
$user.Samaccountname + ',' + $GroupMembership | export-csv c:\scripts\citrix_vendors.csv -NoTypeInformation -Append
but the output Changed from Columns with almost all the info I am grabbing to a single column titled "Length" with a number in each row.

How to update AD Info attribute to list groups user was deleted from?

I have this script that will only list a user's groups on the ISE screen where the data can be copied and pasted elsewhere, but I'm trying to get the group membership names written into the Telephone Notes tab (or Info field). I'm thinking next that these probably need to be turned into string values since I'm getting errors about multi properties not allowed. Here is what I've been trying, but I keep getting errors. Thanks
Import-Module ActiveDirectory
$Users= Import-csv "C:\Scripts\UsersSAM-DisplayName.csv"
ForEach ($User in $Users) {
$SamAccountName=$User.SamAccountName
$DisplayName=$User.DisplayName
$TableFormat= #{E={$_.Name};L="$($DisplayName) - $($SamAccountName)"}
Get-ADUser -Identity $SamAccountName -Properties MemberOf | % {$_.MemberOf } | % {Get-ADGroup -Identity $_ } | % { Set-ADUser -Identity $SamAccountName -add #{info="$_.name"}} | Select Name |
Format-Table $TableFormat }
I figured this out. What they wanted was to first write out a terminated user's groups, then remove those. I did it like this and this code includes the semi-colon so if the user comes back, all you need to do to add them back to all the groups is copy and paste those from the output stored in the Telephones Tab, Notes field. I've also used a trimmed down version of this to export a user's groups to speed up duplicating a user's groups so they match with others on the same team. Hope this helps someone.
Import-csv "$Terms" | % {
$user = Get-ADUser -LDAPFilter ("(sAMAccountName=" + $_.samaccountname + ")") -Properties samaccountname,enabled,name,memberof,distinguishedname,info
#Grab all user group names
$user | ForEach-Object {
$grps = $_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
$arec = $_.Name,$_.SamAccountName
$aline = ($grps -join ";")
#Add info to Notes field Telephone Tab
Get-ADPrincipalGroupMembership -Identity $user | %{
If ($_.SamAccountName -ne "Domain Users") {
$Userinfo=$user.info
Set-ADUser $User -replace #{info= "$Userinfo | $a | Terminated via automated process | $aline"}
#Remove User Groups Process in Telephones Tab Notes Field.
Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_.SamAccountName -Confirm:$false
(" "+ $a +" [" + $User.samaccountname + "], Removed from group [" + $_.samaccountname + "]. ") | Out-File -FilePath $ErrorLog -Append
}
}}}