Combining 2 cmdlets for one result/output using pscustomobject - powershell

Basically what i'm trying to achieve here is an output with 4 column/list (in this case i'm exporting as a text)
Get-MailboxPermission gives me a property of identity, user, accessrights but it doesn't give me a property of "Manager". I need to identify where that particular user reports to. So, i tried PSCustomObject and hoping i can put the results in an array. See script below
$GETMAILBOXPERM = Get-Content C:\Users\Account\Desktop\MailboxUsers\MAILBOXESUSERS.txt | ForEach-Object {Get-MailboxPermission $_ |
where {
($_.User -notlike ‘*NT AUTHORITY*’) -and
($_.User -notlike ‘*S-1-5-21-*’) -and
($_.User -notlike ‘*NAMPRD08*’) -and
($_.User -notlike ‘*PRDTSB01*’) -and
($_.User -notlike ‘*0365Admin*’) -and
($_.User -notlike ‘*Discovery Management*’) -and
($_.User -notlike ‘*NAMPR08A005*’) -and
($_.User -notlike ‘*NT AUTHORITY*’)
}
}
$Results = foreach( $Mailbox in (get-content C:\Users\Account\Desktop\MailboxUsers\MAILBOXESUSERS.txt))
{
$Users = Get-User $Mailbox
if ($Users){
foreach ($User in $Users){
[pscustomobject]#{
DisplayName = $User.name
Account = $GETMAILBOXPERM.user
Manager = $User.manager
Access = $GETMAILBOXPERM.accessrights
}
}
}
}
$Results | Format-List -Property DisplayName, Account, Manager, Access | Out-File C:\Users\Account\Desktop\MailboxUsers\mailbox4.txt
Here's the output in text file. I get the DisplayName and Manager right but the Account and Access just doesn't seem to loop from the text file.
DisplayName : MAILBOX1
Account : {user1#domain.ca, user2#domain.ca, user3#domain.ca, user4#domain.ca...}
Manager : MANAGER1
Access : {FullAccess, FullAccess, FullAccess, FullAccess...}
DisplayName : MAILBOX2
Account : {user1#domain.ca, user2#domain.ca, user3#domain.ca, user4#domain.ca...}
Manager : MANAGER2
Access : {FullAccess, FullAccess, FullAccess, FullAccess...}

The user manager attribute is normally in ADDS, not Exchange. Yet, that text file seems to be where you are getting this from vs dynamically from ADDS.
Why are you using Format-List?
PowerShell will automatically format as a list the moment you columns exceed 5.
This is untested, since I do not have an environment to try it on, but a refactor of what you have here. Give it a shot.
$GetMailboxPerm = Get-Content -Path 'C:\Users\Account\Desktop\MailboxUsers\MAILBOXESUSERS.txt' |
ForEach-Object {Get-MailboxPermission $PSitem |
where {
($PSitem.User -notlike ‘*NT AUTHORITY*|
*S-1-5-21-*|
*NAMPRD08*|
*PRDTSB01*|*0365Admin*|
*Discovery Management*|
*NAMPR08A005*|
*NT AUTHORITY*’)
}
}
foreach( $Mailbox in (Get-Content -Path 'C:\Users\Account\Desktop\MailboxUsers\MailboxUsers.txt'))
{
$Users = Get-User $Mailbox
if ($Users)
{
foreach ($User in $Users)
{
[pscustomobject]#{
DisplayName = $User.name
Account = $GetMailboxPerm.user
Manager = $User.manager
Access = $GetMailboxPerm.accessrights
} | Out-File -FilePath 'C:\Users\Account\Desktop\MailboxUsers\mailbox4.txt' -Append
}
}
}

Related

Get-ADUser - Filter child OU's and users where surname is empty then add to mail-enabled security group

I posted 4 days ago and the community have been really helpful! I can now look for users in a specific parent OU who have a last name.
My second step that I am trying to do is to now add those users who have a last name and are in the parent OU to a mail enabled security group. After some googling I found a piece of script that allows users to be added to such, but I need to edit to to specify my requirements. I thought I had tried to do this but it ended up still searching through the child OUs and adding those without a last name so I must have something wrong or jumbled.
My current script is
$Admin_Accounts = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Service_Accounts = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Disabled = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Test_PowerPoint_GPO = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Exclude = '({0}|{1}|{2})$' -f \[regex\]::Escape($Admin_Accounts), \[regex\]::Escape($Service_Accounts), \[regex\]::Escape($Disabled), \[regex\]::Escape($Test_PowerPoint_GPO)
Get-ADUser -Filter 'Enabled -eq $true' -SearchBase 'OU=Users,OU=Company,DC=CompanyDC,DC=local' |
Where-Object { !\[string\]::IsNullOrWhiteSpace($_.Surname) -and $_.DistinguishedName -notmatch $Exclude } |
Select-Object SamAccountName
$TargetGroup = “Company Team“
$TargetOU = “OU=Users,OU=Company,DC=Company,DC=local“
$Exclude = '({0}|{1}|{2})$' -f \[regex\]::Escape($Admin_Accounts), \[regex\]::Escape($Service_Accounts), \[regex\]::Escape($Disabled), \[regex\]::Escape($Test_PowerPoint_GPO)
$UserAccounts = Get-ADUser -Filter 'Enabled -eq $true' | ?{$_.DistinguishedName -like “_*$TargetOU*” -and $.Enabled -eq “True”}
Where-Object { !\[string\]::IsNullOrWhiteSpace($_.Surname) -and $_.DistinguishedName -notmatch $Exclude } |
Select-Object SamAccountName
ForEach($User in $UserAccounts)
{
$UsersName = $User.Name
\#Check for group membership
$Membership = Get-ADGroup $TargetGroup | Get-ADGroupMember | ?{$\_.Name -eq $UsersName}
if(!$Membership)
{
“Adding $UsersName to $TargetGroup”
Get-ADGroup $TargetGroup | Add-ADGroupMember -Members $User -Verbose
}
}
I tried to add pieces of script to specify my requirements
Seems to me your script is way more complex than it needs to be:
$Admin_Accounts = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Service_Accounts = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Disabled = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
$Test_PowerPoint_GPO = 'OU=Administrators,OU=Company,DC=CompanyDC,DC=local'
# Create regex matching list
[regex]$Exclude = "$Admin_Accounts|$Service_Accounts|$Disabled|$Test_PowerPoint_GPO"
$UserAccounts = Get-ADUser -Filter 'Enabled -eq $true' | Where-Object {
$_.DistinguishedName -like “_*$TargetOU*”
} | Where-Object {
![string]::IsNullOrWhiteSpace($_.Surname) -and $_.DistinguishedName -notmatch $Exclude
} | Select-Object SamAccountName

Powershell - Combining Variables Properties from AD output

First script I have tried to put together. Im trying to get a new variable with ad user name and ad computer by comparing user name property and description properties. I don't know how to pull the properties I want into the new variables based on a compare-object or match. The description property has a setup of username - ######## numbers very.
Variables used (date tell expire)
$SevenDayWarnDate, $ThreeDayWarnDate, $OneDayWarnDate
AD user
$7, $3, $1 -properties "Name", "PasswordExpiry
AD computer
$comp "Name", "Description"
I was then going to make a pop up on user computer based on expiring passwords.
Below is what I was trying to do but im not sure if the needed information was passed as computer filed comes back empty.
$SevenDayWarnDate = (get-date).adddays(7).ToLongDateString()
$7= Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and PasswordLastSet -gt 0 } `
-Properties "Name", "msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "Name", `
#{Name = "PasswordExpiry"; Expression = {[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed").tolongdatestring() }} `
|Where-object -Property PasswordExpiry -EQ $SevenDayWarnDate
$comp = Get-Adcomputer -Filter {Enabled -eq $True} -SearchBase "OU=,DC=" -properties "Name", "Description" `
| Select-Object -Property "Name", "Description"
Compare-Object -ReferenceObject $7 -DifferenceObject $comp -IncludeEqual -ExcludeDifferent -PassThru |
ForEach-Object {
[PSCustomObject]#{
Name = $_.name
Computer = ($comp.name | Where-Object Description -match $_.name).Directory
}
}
Working code based on Santiago Squarzon below.
$dayArray= #()
$dayArray=#(7,3,1)
foreach ($day in $dayArray)
{
$SevenDayWarnDate = (get-date).adddays($day).ToLongDateString()
$filter = "Enabled -eq '$True' -and PasswordNeverExpires -eq '$False' -and PasswordLastSet -gt '0'"
$computerArray= #()
$users = Get-ADUser -Filter $filter -Properties "Name", "msDS-UserPasswordExpiryTimeComputed" |
Select-Object Name, #{
Name = "PasswordExpiry"
Expression =
{
[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed").tolongdatestring()
}
} | Where-object -Property PasswordExpiry -EQ $SevenDayWarnDate
# => It might be better to use:
# PasswordExpiry -ge [datetime]::Now -and PasswordExpiry -le $sevenDayWarnDate
# Find the computers each user is using
$result = foreach($user in $users)
{
$temp=$user.Name
if ($comp = Get-ADComputer -Filter "Description -like '*$temp*'" -Properties Description)
{
[PSCustomObject]#{
Name = $user.Name
PasswordExpiry = $user.PasswordExpiry
ComputerName = $comp.Name
ComputerDescription = $comp.Description
}
$tmpArray= #()
$tmpArray= $comp.Name.Split(" ")
foreach($item in $tmparray)
{
$computerArray += $item
}
$tmpArray = $Null
# }
}
continue
}
foreach($computer in $computerArray)
$tmpMessage =
$tmpMessageTitle =
{Send-RDUserMessage -HostServer $env:COMPUTERNAME -UnifiedSessionID 1 -MessageTitle $tmpMessageTitle -MessageBody $tmpMessage
}
$result | Format-Table
}
Based on the comments and the code in question, I'm guessing this is what you're looking for. There is no need to use Compare-Object, you can simply query Active Directory to get the user's computer based on the Description property.
$SevenDayWarnDate = [datetime]::Now.AddDays(7)
$filter = "Enabled -eq '$True' -and PasswordNeverExpires -eq '$False' -and PasswordLastSet -gt '0'"
$users = Get-ADUser -Filter $filter -Properties "Name", "msDS-UserPasswordExpiryTimeComputed" |
Select-Object Name, #{
Name = "PasswordExpiry"
Expression = {
[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")
}
} | Where-object -Property PasswordExpiry -EQ $SevenDayWarnDate
# => It might be better to use:
# {$_.PasswordExpiry -ge [datetime]::Now -and $_.PasswordExpiry -le $sevenDayWarnDate}
# Find the computers each user is using
$result = foreach($user in $users)
{
if($comp = Get-ADComputer -LDAPFilter "(description=$($user.Name))" -Properties Description)
{
[PSCustomObject]#{
Name = $user.Name
PasswordExpiry = $user.PasswordExpiry
ComputerName = $comp.Name
ComputerDescription = $comp.Description
}
continue
}
Write-Host "No computer was found for User: $($user.Name)"
}
$result | Format-Table

Get-ADUser is not returning anything when I use the UPN returned from Get-MailboxPermissions as a variable

I am trying to get the SamAccountName from Get-ADUser, but when I pass in the variable $member.User I get no results. $member.User when I print it out with Write-Host returns a variable, but used in the code below I get nothing. Also, if I copy/paste the $member.User value into that $add = Get-ADUser I get the SamAccountName. Why isn't Get-ADUser -Filter {EmailAddress -eq "$member.User" } returning anything? It is driving me nuts. Thank you in advance.
$Send = #()
$SendAs = #()
# Displaying FullAccess permissions for shared mailboxes
$Send = Get-MailboxPermission -Identity $MailboxUPN | Where-Object { -not ($_.User -like “NT AUTHORITY\SELF”) } | Select-Object Identity,User,AccessRights
$Send
# Displaying SendAs permissions for shared mailboxes
# $SendAs = Get-RecipientPermission -Identity $MailboxUPN | Where-Object {($_.IsInherited -eq $False) -and -not ($_.Trustee -like “NT AUTHORITY\SELF”) } | Select-Object Trustee, AccessRights
# $SendAs
forEach ($member in $Send){
Write-Host "In here"
Write-Host $member
$add = Get-ADUser -Filter {EmailAddress -eq "$member.User" }| Select-Object -ExpandProperty SamAccountName
Write-Host $add.SamAccountName
}

Exchange 2010 Powershell - Return Users With SendAs Permissions But Filter Disabled Users

so I have a script that works fine that I found online and changed to suit my needs. I have pasted this script below. However, in the output there is a lot of disabled users that have permissions to the mailboxes. E.g. I'd get an Output like "Mailbox Name^Mailbox#email.com^ActiveUser ActiveUser DisabledUser" So I am wondering if there is a way to make the script skip disabled users, same way how it leaves out self permissions.
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
. $env:ExchangeInstallPath\bin\RemoteExchange.ps1
Connect-ExchangeServer -auto
$OutFile = “C:\Send_As_Permissions.txt”
“DisplayName” + “^” + “Email Address” + “^” + “Send As” | Out-File $OutFile -Force
$Mailboxes = Get-Mailbox -resultsize unlimited | Select Identity, Alias, DisplayName, DistinguishedName, WindowsEmailAddress
ForEach ($Mailbox in $Mailboxes) {
$SendAs = Get-ADPermission $Mailbox.identity | where {($_.ExtendedRights -like “*Send-As*”) -and -not ($_.User -like “NT AUTHORITY\SELF”) -and -not ($_.User -like “s-1-5-21*”)} | % {$_.User}
$Mailbox.DisplayName + “^” + $Mailbox.WindowsEmailAddress + “^” + $SendAs | Out-File $OutFile -Append
}
If you want to report on enabled mailboxes only, filter the output from Get-Mailbox on the IsMailboxEnabled property:
$Mailboxes = Get-Mailbox -resultsize unlimited | Where-Object { $_.IsMailboxEnabled } | Select ...
If you want to report on individual rights assignments for enabled accounts only, you'll have to query AD based on the value of the User property you extract:
$SendAs = Get-ADPermission $Mailbox.identity | where {($_.ExtendedRights -like “*Send-As*”) -and -not ($_.User -like “NT AUTHORITY\SELF”) -and -not ($_.User -like “s-1-5-21*”)} | % {$_.User}
$domain,$username = $SendAs.Split('\')
$ADUser = Get-ADUser -Identity $username -Server $domain
if($ADUser.Enabled){
# output to report
}

Combine multiple foreach results into a single report

$results = foreach ($Mailbox in (Get-Mailbox -ResultSize Unlimited))
{
get-MailboxFolderPermission -identity "$($Mailbox.Name):\Calendar" -ErrorAction SilentlyContinue |
Where-Object {$_.User -notlike "Default" -and
$_.User -notlike "Anonymous" -and
$_.AccessRights -notlike "None" -and
$_.AccessRights } |
Select #{N="Mailbox";E={$Mailbox.SamAccountName}}, FolderName, User, AccessRights
}
$results
I am still learning powershell (only 1 full year of experience). I'm using this code to report on calendar permissions for all end user mailboxes in our environment. The code works well but it only reports on the Calendar object. I need to run three separate reports to get the Calendar, Contacts, and Inbox permissions.
I have tried creating an array but it throws multiple values all on one line. (Some end users have more than one person with access to their Calendar/Contacts/Inbox. Does anyone have a good idea of how to combine these results?
thanks
Here is an example of what results I would like:
Iterating Mailboxes only once with an additional
ForEach ($Folder in 'Contents','Calendar','Inbox')
Should be more efficient:
#Date
$date = (Get-Date -f yyyy-MM-dd)
#Pull Permissions
$Permissions = ForEach ($Mailbox in (Get-Mailbox -ResultSize Unlimited )) {
ForEach ($Folder in 'Contents','Calendar','Inbox'){
Get-MailboxFolderPermission -identity "$($Mailbox.Name):\$($Folder)" -ErrorAction SilentlyContinue |
Where-Object {$_.User -notlike "Default" -and $_.User -notlike "Anonymous" -and $_.AccessRights -notlike "None" -and $_.AccessRights } |
Select #{N="Mailbox";E={$Mailbox.SamAccountName}},
#{N="Folder";E={$_.FolderName}},
#{N="User With Access";E={$_.User}},
#{N="Access";E={$_.AccessRights}}
}
}
#Export to Desktop
$Permissions | Sort User | Export-Csv "$env:USERPROFILE\Desktop\ExchangePermissions-$Date.csv" -NoTypeInformation
#Date
$date = (Get-Date -f yyyy-MM-dd)
#Pull Permissions
$Permissions = ForEach ($Mailbox in (Get-Mailbox -ResultSize Unlimited )) {
$userInfo = get-user $Mailbox.name | select Title
ForEach ($Folder in 'Contacts','Calendar','Inbox'){
Get-MailboxFolderPermission -identity "$($Mailbox.Name):\$($Folder)" -ErrorAction SilentlyContinue |
Where-Object {$_.User -notlike "Default" -and $_.User -notlike "Anonymous" -and $_.AccessRights -notlike "None" -and $_.AccessRights } |
Select #{N="Mailbox";E={$Mailbox.SamAccountName}},
#{N="Office";E={$Mailbox.Office}},
#{N="Title";E={$userInfo.Title}},
#{N="Folder";E={$_.FolderName}},
#{N="User With Access";E={$_.User}},
#{N="Access";E={$_.AccessRights}}
}
}
#Export to Desktop
$Permissions | Sort User | Export-Csv
"$env:USERPROFILE\Desktop\ExchangePermissions-$Date.csv" -NoTypeInformation