Labels

Sunday, June 14, 2020

Exchange PowerShell Commands #2

Well it's 2020, and instead of flying around in a hovercar I'm *still* doing IT. Trying to get back in the swing of things – and following on from the last post seven year ago (!?), here's an additional 64 Exchange commands circa Exchange 2013/2016.

Each command can be copied and pasted into a PowerShell command line running with an Exchange PSSession, although at the time I made notes on a couple of them about running locally on the server due to cmdlet or type casting limitations.



Remove an existing Exchange 2010 move request (to allow subsequent moves)
Remove-MoveRequest -id user01

Initiate an Exchange 2010 intra-org move request
new-moverequest -id user01 -TargetDatabase db02

Output semi-colon delimited list of email addresses for a mailbox
[string]::Join(';',$mailbox.emailaddresses)

Convert a mailbox to a standard user mailbox
get-mailbox user01 | set-mailbox -type regular -whatif

Modify permissions to allow modifying apply policy attributes of user objects
Add-ADPermission -Identity "OU=Resources,DC=domain,DC=local" -InheritanceType Descendents -InheritedObjectType user -AccessRights ReadProperty, WriteProperty -Properties msExchPoliciesIncluded, msExchPoliciesExcluded -User "domain\group1" -domaincontroller dc01

Disable an Exchange 2007 mailbox - leaving the user account in AD
Disable-Mailbox -id user01

Reapply the mandantory properties on a mailbox (changing from linked to normal)
set-mailbox -id $account -applymandatoryproperties  #Clearing AEA and master account SID resets the isLinked property of the mailbox, but RecipientTypeDetails / RecipientDisplayType is not automatically updated.  Re-applying mandatory properties corrects this issue and sets the mailbox back to being a user mailbox instead of a linked mailbox

Find Exchange 2010 DAG status
Get-DatabaseAvailabilityGroup -status | fl *

Find Exchange 2010 DAG replication status
$servers = Get-MailboxServer; foreach ($server in $servers) { Get-MailboxDatabaseCopyStatus -server $server.name}

Find the mailbox activation preference for an Exchange 2010 mailbox database
(Get-MailboxDatabase -id MBXDB1).ActivationPreference

Report the last 1000 commands executed
Get-history -count 1000

Reseed the content index catalog for the database copy
Update-MailboxDatabaseCopy "DB\SERVER" -CatalogOnly

Get the mailbox database copy status
Get-MailboxServer | Get-MailboxDatabaseCopyStatus -ExtendedErrorInfo | sort-object ContentIndexState | fl Name,ContentIndexState,ContentIndexErrorMessage

Convert a user mailbox to a linked mailbox without disabling
Set-User -id user01 -LinkedMasterAccount domainb\user01 -LinkedDomainController dc01.domainb.com -LinkedCredential $domainbcred # may need get-mailbox -id user01 | set-mailbox -type regular; get-mailbox -id user01 | set-mailbox -ApplyMandatoryProperties

Find the current owner of Exchange 2010 mailbox databases
dsquery * "CN=Databases,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,CN=Dept,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=domain,DC=local" -filter (objectclass=msExchMDB) -attr Name msExchOwningServer -s dc2

Mount an Exchange 2010  public folder database
Get-PublicFolderDatabase -id 'Public Folder Database 1' | mount-database

Find an Exchange 2010 Primary Active Manager for the specified DAG
Get-DatabaseAvailabilityGroup -Status | fl PrimaryActiveManager

Configure the Exchange 2010 postamaster address
Get-TransportConfig | fl -ExternalPostmasterAddress; Set-TransportConfig -ExternalPostmasterAddress postmaster@domain.com

Enumerate outlook profiles to find connected mailboxes and calendars
EnumOutlookProfiles.ps1

Find if an Exchange 2010 mailbox is enabled for ActiveSync
get-casmailbox -id user1

Set Exchange 2010 calendar processing to anyone can book and autoaccept
Set-CalendarProcessing -Identity room01 -AutomateProcessing AutoAccept -AllBookInPolicy $true

Get Exchange 2010 mailbox calendar configuration
Get-MailboxCalendarConfiguration -id room01 | fl *

Force an update of the offline address book
Update-OfflineAddressBook -id 'Default Offline Address List'

Exchange query for Global Security groups
get-group -filter "GroupType -eq $([Microsoft.Exchange.Data.Directory.Recipient.GroupTypeFlags]::SecurityEnabled.value__ + [Microsoft.Exchange.Data.Directory.Recipient.GroupTypeFlags]::Global.value__)"; #get-group -filter {GroupType -eq '-2147483646'}

Exchange query for Domain Local Security groups
get-group -filter "GroupType -eq $([Microsoft.Exchange.Data.Directory.Recipient.GroupTypeFlags]::SecurityEnabled.value__ + [Microsoft.Exchange.Data.Directory.Recipient.GroupTypeFlags]::DomainLocal.value__)"; #get-group -filter {GroupType -eq '-2147483644'}

Exchange query for Universal Security groups
get-group -filter "GroupType -eq $([Microsoft.Exchange.Data.Directory.Recipient.GroupTypeFlags]::SecurityEnabled.value__ + [Microsoft.Exchange.Data.Directory.Recipient.GroupTypeFlags]::Universal.value__)"; #get-group -filter {GroupType -eq '-2147483640'}

Set Out Of Office on a mailbox
Set-MailboxAutoReplyConfiguration 'user1' -AutoReplyState enabled -ExternalAudience all -InternalMessage "Internal not Here" -ExternalMessage "External not here"

Get a role group from the root of the forest
Get-RoleGroup -id Exchange-Lvl1Support -DomainController dc1.forest.root

Get a role group and the roles and role assignments
$rg = Get-RoleGroup -id Exchange-Lvl1Support -DomainController dc1.forest.root; $rg.roles; $rg.roleassignments

Get a management scope to show the recipient root and filter
Get-ManagementScope -id MS-Exchange_Distribution-Groups | fl *

Get the management role assignments for the specified assignee
Get-ManagementRoleAssignment | where {$_.RoleAssigneeName -like '*Exchange-Lvl1Support*'} | ft -wrap -auto

Get the management role assignment to confirm the CustomRecipientWriteScope
Get-ManagementRoleAssignment -id Distribution-GroupCreation | fl *

Expand the e-mail addresses of a mailbox to one per line
get-mailbox -id user1 | select -expand emailaddresses

Find Distribution List expansion
$expandDL = foreach ($server in Get-TransportServer) {Get-MessageTrackingLog -EventID EXPAND -resultsize unlimited -server $server | select "Timestamp","ServerHostname","EventId",{$_.RelatedRecipientAddress},{$_.Sender},"MessageSubject"}

Convert a mailbox from linked to resource
$ADsPath = "LDAP://CN=user1,OU=Shared Mailboxes,DC=domain,DC=local"; $user = [ADSI]$ADsPath ; $user.putex(1,"msExchMasterAccountSid",$null); $user.setinfo(); get-mailbox -id user1 | set-mailbox -ApplyMandatoryProperties; get-mailbox -id user1 | set-mailbox -type shared

Find mailboxes on a specific version of exchange (2010)
$mailboxes = get-mailbox -filter {ExchangeVersion -eq 44220983382016} -resultsize unlimited

Find the Exchange 2010 SP1+ Address Book RPC port
reg query \\cas1\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\MSExchangeAB\ParametersSystem /v RpcTcpPort

Find the Exchange 2010 RPC port
reg query \\cas1\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\MSExchangeRPC\ParametersSystem /v "TCP/IP Port"

Mail-enable an existing AD contact
Enable-MailContact -id "CN=User 01,OU=Contacts,DC=domain,DC=local" -ExternalEmailAddress user@somewhere.com

Modify the MRS mailbox replication for move requests
notepad "\\cas1\c$\Program Files\Microsoft\Exchange Server\V14\Bin\MSExchangeMailboxReplication.exe.config" (MaxActiveMoves* and MaxTotalMovesPerMRS)

Find Exchange 2010 recoverable deleted items
Get-MailboxFolderStatistics -Identity "user@domain.com" -FolderScope RecoverableItems | ft -wrap -auto

Export mailbox to PST in EX2010 (requires Exchange Trusted Subsystem ACLs)
New-MailboxExportRequest -Mailbox user@domaincom -FilePath \\cas1\d$\martinwa.pst

Check the move history of a mailbox
get-mailboxstatistics -id "CN=user1,DC=domain,DC=local" -includemovehist | fl Identity,MoveHistory

Check Exchange 2010 logon statistics to see who is logging on to a mailbox
get-mailbox -id user1 | get-logonstatistics | ft UserName,ServerName,LogonTime,LastAccessTime,Windows2000Account -wrap -auto

Set mailbox delivery restrictions to only allow accepting messages from (ndr)
Set-Mailbox -Identity user1 -AcceptMessagesOnlyFrom @{add="user2"} -whatif

Use Exchange 2010 cmdlets to change the CN/DisplayName of a security group
get-adgroup -id oldsamid | set-adgroup -SamAccountName newsamid -whatif

Find safe and blocked senders configured through Outlook for each mailbox
$mailboxes | Get-MailboxJunkEmailConfiguration | export-csv -path c:\temp\JunkEmailConfiguration_20140625.csv

Delete all the items from an Exchange 2010 mailbox
Search-Mailbox -id user@domain.com -DeleteContent -confirm:$false -force

restore specific folders from a disconnect mailbox data to a recovery mailbox
New-MailboxRestoreRequest -BatchName Recovery -Name Test.User -SourceDatabase 'MBXDB5' -SourceStoreMailbox "2e94ffc9-9dad-42b1-92ec-5767d11051e4" -excludedumpster -includeFolders "Contacts/Misc", "Contacts/MISC/SHOPPING", "Contacts/MISC/Work Related" -TargetMailbox "recovery1" -AllowLegacyDNMismatch -whatif

Find Exchange 2010 RBAC management role entries for the specified role
Get-ManagementRole  -id RecipientCreationUserMailboxes | select -expand roleentries;  $entries = (Get-ManagementRole  -id RecipientCreationMailUser).RoleEntries; $entries | %{$_.split()[1]}

Find Exchange 2010 RBAC management scope OU and filter for the specified scope
Get-ManagementScope -id Managed-Users_UserMailboxes  | fl Identity,RecipientFilter,RecipientRoot

Search Exchange 2010 Admin Audit log for changes made by Exchange
Search-AdminAuditLog | ft -wrap -auto

export Exchange 2010 Admin Audit Log for new-mailbox requests and callers
$newUsers = Search-AdminAuditLog -cmdlets New-Mailbox,New-MailUser; $newUsers | select RunDate,ObjectModified,CmdletName,Caller,OriginatingServer | export-csv -path c:\temp\ExchangeUsers_20141020.csv -encoding ascii

Get Exchange mail queues on the specified server
get-queue -Server mail02

Get Exchange mail queue information
get-queue -Identity MAIL02\281950 | fl DeliveryType,NextHopDomain,Status,MessageCount,LastError

Find disconnected mailboxes (run on console of exchange server, not session)
get-mailboxdatabase | Get-MailboxStatistics | where {$_.displayName -eq 'User 01' -and $_.DisconnectDate -ne $null}

Report AD permissions through Exchange cmdlets
Get-ADPermission -id "OU=Distribution Lists,OU=Resources,DC=domain,DC=local" |ft Identity,User,InheritedObjectType,ExtendedRights,Properties,ChildObjectTypes,AccessRights -wrap -auto

Add an address to an exchange 2010 object
Set-MailUser -id "user1" -EmailAddresses (((Get-MailUser -id "user1").EmailAddresses)+="smtp:usernew@domain.com") -whatif

Remove an address from an exchange 2010 object
$recipient = "user1"; $remove = "smtp:usernew@domain.com"; Set-MailUser -id $recipient -EmailAddresses ((Get-MailUser -id $recipient).EmailAddresses | where {$_ -ne $remove}) -whatif

Remove an address from an exchange 2010 object with AD cmdlets
$recipient = "user1"; $remove = "smtp:usernew@domain.com"; Set-ADUser -id $recipient -replace @{proxyAddresses=([system.object[]](Get-ADUser -id $recipient -prop proxyAddresses | Update-List -Property proxyAddresses -Remove $remove).proxyaddresses)} -whatif

Find Outlook Auto Mapping attributes for links/backlinks
get-adobject -LDAPFilter "(&(objectclass=user)(objectcategory=person)(|(msexchdelegatelistbl=*)(msexchdelegatelistlink=*)))" -prop displayname,msexchdelegatelistbl,msexchdelegatelistlink | select displayname,msexchdelegatelistbl,msexchdelegatelistlink | ft -wrap -auto

Exchange cmdlet to query the UPN suffix list
Get-UserPrincipalNamesSuffix

Find people that have upgrated to iOS 7.0 on EAS connected devices
get-adobject -ldapfilter "(&(objectClass=msExchActiveSyncDevice)(objectCategory=msExchActiveSyncDevice)(msExchDeviceOS=ios*7.0*))" -prop msExchDeviceOS,canonicalName -server dc1

Apply a throttling policy association to a standard user or MEU
Set-ThrottlingPolicyAssociation -Identity svc_mw -ThrottlingPolicy Office365MigrationWiz

Wayne's World of IT (WWoIT). 

No comments:


All Posts

printQueue AD objects for 2003 ClusterVirtualCenter Physical to VirtualVirtual 2003 MSCS Cluster in ESX VI3
Finding duplicate DNS recordsCommand-line automation – Echo and macrosCommand-line automation – set
Command-line automation - errorlevels and ifCommand-line automation - find and findstrBuilding blocks of command-line automation - FOR
Useful PowerShell command-line operationsMSCS 2003 Cluster Virtual Server ComponentsServer-side process for simple file access
OpsMgr 2007 performance script - VMware datastores...Enumerating URLs in Internet ExplorerNTLM Trusts between 2003 and NT4
2003 Servers with Hibernation enabledReading Shortcuts with PowerShell and VBSModifying DLL Resources
Automatically mapping printersSimple string encryption with PowerShellUseful NTFS and security command-line operations
Useful Windows Printer command-line operationsUseful Windows MSCS Cluster command-line operation...Useful VMware ESX and VC command-line operations
Useful general command-line operationsUseful DNS, DHCP and WINS command-line operationsUseful Active Directory command-line operations
Useful command-linesCreating secedit templates with PowerShellFixing Permissions with NTFS intra-volume moves
Converting filetime with vbs and PowerShellDifference between bat and cmdReplica Domain for Authentication
Troubleshooting Windows PrintingRenaming a user account in ADOpsMgr 2007 Reports - Sorting, Filtering, Charting...
WMIC XSL CSV output formattingEnumerating File Server ResourcesWMIC Custom Alias and Format
AD site discoveryPassing Parameters between OpsMgr and SSRSAnalyzing Windows Kernel Dumps
Process list with command-line argumentsOpsMgr 2007 Customized Reporting - SQL QueriesPreventing accidental NTFS data moves
FSRM and NTFS Quotas in 2003 R2PowerShell Deleting NTFS Alternate Data StreamsNTFS links - reparse, symbolic, hard, junction
IE Warnings when files are executedPowerShell Low-level keyboard hookCross-forest authentication and GP processing
Deleting Invalid SMS 2003 Distribution PointsCross-forest authentication and site synchronizati...Determining AD attribute replication
AD Security vs Distribution GroupsTroubleshooting cross-forest trust secure channels...RIS cross-domain access
Large SMS Web Reports return Error 500Troubleshooting SMS 2003 MP and SLPRemotely determine physical memory
VMware SDK with PowershellSpinning Excel Pie ChartPoke-Info PowerShell script
Reading web content with PowerShellAutomated Cluster File Security and PurgingManaging printers at the command-line
File System Filters and minifiltersOpsMgr 2007 SSRS Reports using SQL 2005 XMLAccess Based Enumeration in 2003 and MSCS
Find VM snapshots in ESX/VCComparing MSCS/VMware/DFS File & PrintModifying Exchange mailbox permissions
Nested 'for /f' catch-allPowerShell FindFirstFileW bypassing MAX_PATHRunning PowerSell Scripts from ASP.Net
Binary <-> Hex String files with PowershellOpsMgr 2007 Current Performance InstancesImpersonating a user without passwords
Running a process in the secure winlogon desktopShadow an XP Terminal Services sessionFind where a user is logged on from
Active Directory _msdcs DNS zonesUnlocking XP/2003 without passwords2003 Cluster-enabled scheduled tasks
Purging aged files from the filesystemFinding customised ADM templates in ADDomain local security groups for cross-forest secu...
Account Management eventlog auditingVMware cluster/Virtual Center StatisticsRunning scheduled tasks as a non-administrator
Audit Windows 2003 print server usageActive Directory DiagnosticsViewing NTFS information with nfi and diskedit
Performance Tuning for 2003 File ServersChecking ESX/VC VMs for snapshotsShowing non-persistent devices in device manager
Implementing an MSCS 2003 server clusterFinding users on a subnetWMI filter for subnet filtered Group Policy
Testing DNS records for scavengingRefreshing Computer Account AD Group MembershipTesting Network Ports from Windows
Using Recovery Console with RISPAE Boot.ini Switch for DEP or 4GB+ memoryUsing 32-bit COM objects on x64 platforms
Active Directory Organizational Unit (OU) DesignTroubleshooting computer accounts in an Active Dir...260+ character MAX_PATH limitations in filenames
Create or modify a security template for NTFS perm...Find where a user is connecting from through WMISDDL syntax in secedit security templates

About Me

I’ve worked in IT for over 20 years, and I know just about enough to realise that I don’t know very much.