Writing a mailbox property to a Variable or text box - powershell

I am writing a basic GUI that makes it easier for staff to find current mailbox/calendar rights. Essentially they type the name of the mail box and the user who's permissions they wish to check, and it writes what the permissions are
I have tried two ways and both ran into problems. The first:
$Property = get-mailboxpermission -Identity $Mailbox -User $User | Format-List AccessRights if($Property -eq "AccessRights : {FullAccess}")
$PermissionText.AppendText(($Property))
Results with the output:
"Microsoft.PowerShell.Commands.Internal.Format.FormatStartData....."
(I have also get the same when simply inputting the get-mailbox command to the append text)
I have also tried instead to convert the access rights property to a variable, then writing that to the text box using if conditions as below code, but that doesn't play nice either
Method:
$Property = get-mailboxpermission -Identity $Mailbox -User $User | format-list AccessRights
if($Property -eq "AccessRights : {FullAccess}")
{$PermissionText.AppendText("Full Access")}
if($Property -eq "AccessRights : {ReadAccess}")
{$PermissionText.AppendText("Read Only")}
Output: Nothing whatsoever
in short, I need a way of either outputting just the permissions to the text box, or, making the variable equal something useable

Try this:
$Property = Get-MailboxPermission -Identity $Mailbox -User $User | ? {$_.AccessRights -eq "FullAccess"}
if($Property)
{
$PermissionText.AppendText($Property.User.ToString())
}

Thankyou #Avshalom i figured it from your idea:
$Property = Get-MailboxPermission -Identity $Mailbox -User $User | ? {$_.AccessRights}
$PermissionText.AppendText($Permission.AccessRights)

Related

Looping Through All Calendars With Get-MailboxFolderPermission

I have researched this extensively and used much trial-and-error, but I have yet to get a scrip to work that performs the function I want it to. What I want is to create a script that will allow the user to type a username, and then run through all the mailboxes and show the user's permissions on those user's calendars. I've gotten very close with the below script, but this only works on the mailbox as a whole, and does not work if I simply add ":\Calendar" to the $Box variable. Any input on how to get this to show the calendar permissions would be welcome.
$Username = Read-Host "Enter the user whose access you would like to view"
foreach ($Box in Get-Mailbox) {
Get-MailboxFolderPermission -Identity $Box -User $Username
}
I know this is a repeat of a previous question, but as I've altered my code significantly, I thought it was worth asking again. Here's the link to my prior question:
Exchange Powershell: Get-MailboxFolderPermission for all calendars
Thanks for any help!
You could refer to the below code:
(Get-Mailbox) | ForEach-Object {
Get-Mailboxfolderpermission (($_.PrimarySmtpAddress)+":\calendar") `
-User happyboy -ErrorAction SilentlyContinue
} | Select-Object Identity, User, Accessrights
For more information, please refer to this link:
Display all mailbox calendars which a user has access to
Using the suggestion by #Alina-Li, I was able to work out the following code. Everything works well now:
(Get-Mailbox) | ForEach-Object {
$Permission = Get-Mailboxfolderpermission ($_.PrimarySMTPAddress.Local + "#" + $_.PrimarySMTPAddress.Domain +":\calendar") `
-User $User -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Accessrights
if ($Permission -ne $null) {
echo ("Calendar: "+($_.Name))
echo ($User+"'s Permission: "+$Permission)
echo ""
}
}

Powershell Pipeline Argument not gettings passed to Set-ADUser

I've been banging my head against the wall for the past few hours, I'm sure it's because I don't quite understand something about how #{} and $_ work.
First the code:
Get-ADUser username -Properties mail | Set-ADUser -replace #{"proxyaddresses"="SMTP:"+$_.mail}
As you can see I'm trying to update the proxyaddresses fields with the user's email address.
Instead only the string is pulled:(output: proxyaddresses : {SMTP:}) and the pipeline is ignored, I'm assuming it's because it's empty for some reason, but it's not clear to me why.
I've tried variations such as "proxyaddresses="SMTP:$($_.mail)" I tried using default properties that are always sent with Get-ADUser such as UserPrincipalName
I know that something like this is possible because of this http://www.itprotoday.com/management-mobility/more-flexible-active-directory-one-liner and mutiple answers on SO using some variation of the linked example.
When I assign a variable to SMTP:$_.mail and then use that in the field instead like so:
Get-ADUser username -Properties mail | %{ $smtp = "SMTP:"+$_.mail
$_|Set-ADUser -replace #{"proxyAddresses"=$smtp}
This works (output: proxyaddresses :{SMTP:emailaddress#domain.com}). If I leave out the string like so: #{"proxyaddresses"=$_.mail}
I get the following error:
Set-ADUser : Cannot bind parameter 'Replace' to the target. Exception setting "Replace": "Object reference not set to an instance of an object."
At line:1 char:58
I'm not sure what this means.
I'd like some variation of my initial idea to work, but I'll settle for the workaround using an extra variable if there's no other way.
EDIT: There seems to be some confusion about what I'm asking, so I'll clarify:
Is there a way to use the pipeline variable $_ without a script block inside a hashtable, (inside a script block requires double piping like #TheIncorrigible1 suggested in his first answer.)?
EDIT: Based on this it seems this should not be having any issues.
You need to use ForEach-Object to access the pipeline in the way you're trying, otherwise it doesn't know what your pipeline object ($_) is:
Get-ADUser -Identity username -Properties mail |
ForEach-Object {
$_ | Set-ADUser -Replace #{ 'proxyaddresses' = 'SMTP:' + $_.mail }
}
Or the -PipelineVariable common parameter which explicitly assigns $_ to a variable:
Get-ADUser -Identity username -Properties mail -PipelineVariable user |
Set-ADUser -Replace #{ ProxyAddresses = "SMTP:$($user.mail)" }
ProxyAddresses is an array where the Primary Email address is set like SMTP:primary#example.com but there can and will be other elements there too like alias email addresses (that have the lowercase smtp: prefix), SIP: addresses etc.
NEVER try to simply overwrite whatever is already there by a single string found in the mail attribute of the user object, but merge them with the ones you want to add. Selectively replace the ones you want to be changed and build an array of valid addresses.
Basically you do
$oldErrorAction = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
$user = Get-AdUser -Identity $SAMAccountName -Properties mail
$primaryEmailAddress = $user.mail
$externalAddress = "smtp:<WHATEVER ALIAS YOU WOULD LIKE FOR THE USER">
$mailProxies = #("SMTP:$primaryEmailAddress", "smtp:$externalAddress")
# add more to this array if need be
$newProxies = #{'ProxyAddresses' = $mailProxies}
try {
$user | Set-ADUser -Clear ProxyAddresses
$user | Set-ADUser -Add $newProxies
}
catch {
Write-Warning "Could not set ProxyAddresses: $($_.Exception.Message)"
}
$ErrorActionPreference = $oldErrorAction
You may want to try set the variable first and then call on it in the script.
something like this,
$user = Get-ADUser username -Properties mail | select-object mail
Then write your script and call on the variable you may need to use foreach with a if statement to get it to function the way you want.

Determining if a given user is in a given global group

I’m trying to search through Active Directory using the AD module in PowerShell. I’m trying to determine whether a given user is in a given global group. The issue is that I’m using -match meaning if there is a username that contains another within it, such as 'smith_pl' containing 'smith_p'. The user 'smith_p' will be shown to be in the group.
So my question is: Is there a better way of getting a $True or $False return depending if a user is in a giving global group using the AD module?
If not
Is there a way of getting the output from $ListOfmembers into an array so I can use -eq instead of -match?
Part of Script:
$ListOfmembers = dsquery group domainroot -name $globalgroup |
dsget group -members |
dsget user -samid -L
$checkMember = $False
#Search if the user is in output the list
If($ListOfmembers -match $Logonname){
$checkMember = $True
}
ListOfmembers Output:
samid: user05_t
samid: user23_s
samid: Admin
samid: user45_s
dsget succeeded
Any help would be appreciated, Cheers.
$member = Get-ADGroupMember group1 -Recursive | where {$_.samaccountname -eq 'user1'}
if($member) {'user 1 is a member of group1'}
You can do it like this:
[reflection.assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement")
$username = "samaccountname"
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ct, $username)
$g = $user.GetGroups()
( $g | select -expa name ) -contains 'groupname'
You should checkout QAD: http://www.quest.com/powershell/activeroles-server.aspx
$user get-qaduser samAccountName
$user.memberof

Powershell pipeline - Retrieve outputs from first cmdlet?

I am trying a few things in Powershell and what I don't manage to achieve is the following (in Exchange):
Get-User | Get-MailboxStatistics
But in the output I would like some fields/outputs from the "Get-User" cmdlet and some fields/outputs from the "Get-MailboxStatistics" cmdlet.
If anyone has an answer, I have searched the web but with no success as I've had difficulties explaining it in a few words.
Thanks in advance for your help.
Start with the execution of one cmdlet, pipe the results to Foreach-Object and then save a reference to the current object ($user), now execute the second command and save it in a variable as well. Create new object with properties from both objects.
You also need to filter users that have mailboxes, use the RecipientTypeDetails parameter.
$users = Get-User -RecipientTypeDetails UserMailox
$users | Foreach-Object{
$user = $_
$stats = Get-MailboxStatistics $user
New-Object -TypeName PSObject -Property #{
FirstName = $user.FirstName
LastName = $user.LastName
MailboxSize = $stats.TotalItemSize
ItemCount = $stats.ItemCount
}
}
I don't know if it is the best or optimal solution, but you certainly do it by saving actual user to variable in foreach:
$users = Get-User
$users | % { $user = $_; Get-MailboxStatistics $_ | %
{
"User name:{0} - some mailbox statistics: {1}" -f $user.SomePropertyOfUser, $_.SomePropertyOfMailbox
}
}
The first step (saving users into separate variable) is required only when working with Exchange cmdlets - as mentioned here, you cannot nest Exchange cmdlets in foreach...
This error is caused when executing the Exchange cmdlets through PowerShell remoting, which do not support more than one pipeline running at the same time. You may see this error when you pipe the output from a cmdlet to foreach-object, which then runs another cmdlet within its scriptblock.
$users = Get-User -RecipientTypeDetails UserMailbox
$users | Foreach-Object{ $user = $_; $stats = Get-MailboxStatistics $user.DistinguishedName; New-Object -TypeName PSObject -Property #{FirstName = $user.FirstName; LastName = $user.LastName;MailboxSize = $stats.TotalItemSize;ItemCount = $stats.ItemCount }}
I've had to add a specific field in input of Get-MailboxStatistics because remotely, I was having:
The following Error happen when opening the remote Runspace: System.Management.Automation.RemoteException: Cannot process argument transformation on parameter 'Identity'. Cannot convert the "gsx-ms.com/Users/userName1" value of type "Deserialized.Microsoft.Exchange.Data.Directory.Management.User" to type "Microsoft.Exchange.Configuration.Tasks.GeneralMailboxOrMailUserIdParameter".
Anyway, thank you both #Jumbo and #Shay-levy
Get-ADUser -identity ADACCOUNT | Select-object #{Name="Identity";Expression={$_.SamAccountName}} | Get-MailboxStatistics
For some reason the Identity parameter doesn't take pipelne input by value, only by property name. So in order to get it to work you can change the name of piped in data to match the parameter name of Identity. Then Get-MailboxStatistics finally knows how to treat the data your feeding it via the pipeline.

exchange powershell : parsing an array boolean value

In my output, I get
#{ActiveSyncEnabled=False}
how do I parse this so that it just says "False"?
the output is coming from this line of code:
$pda = get-casmailbox -Anr $user.displayname | select activesyncenabled
To access the value directly:
(get-casmailbox -Anr $user.displayname).activesyncenabled
You can skip anr and use the identity member:
Get-CASMailbox $user.Identity
To get all activesyncenabled enabled mailboxes:
get-casmailbox -resultSize unlimited -filter {activesyncenabled -eq $true}
I don't have access to an exchange box right now, but the information should be there now for someone that does. Here is what worked:
$pda = get-casmailbox -Anr $user.displayname | select activesyncenabled
$pda.ActiveSyncEnabled | Write-Host