Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

PowerShell Tips & Tricks for Exchange

593 views

Published on

IT/DEV Connections 2014
by Jaap Wesselius & Michel de Rooij

Published in: Technology
  • Be the first to comment

PowerShell Tips & Tricks for Exchange

  1. 1. PowerShell Tips & Tricks for Exchange #devconnections
  2. 2. POWERSHELL TIPS & TRICKS FOR EXCHANGE Agenda • Introduction • Exchange & PowerShell • Tips & Tricks – PowerShell scripting – Cmdlet Extension Agents • Demo #devconnections
  3. 3. POWERSHELL TIPS & TRICKS FOR EXCHANGE • Jaap Wesselius • Independent Consultant • Exchange MVP (8yrs) • jaap@wesselius.info • @jaapwess • www.jaapwesselius.com • Michel de Rooij • Consultant @ Conclusion FIT • Exchange MVP • michel@eightwone.com • @mderooij • www.eightwone.com • TheUCArchitects.com #devconnections
  4. 4. POWERSHELL TIPS & TRICKS FOR EXCHANGE Introduction • Who attended Sigi Jagott’s session? • PowerShell is a command-line environment • First introduced for Windows 2003 – Codename ‘Monad’ • Exchange Management Shell is add-on for PowerShell #devconnections
  5. 5. POWERSHELL TIPS & TRICKS FOR EXCHANGE Exchange & PowerShell • On-Premises – PowerShell 1.0 (EX2007) – PowerShell 2.0 (EX2010) – PowerShell 4.0 (EX2013) • Exchange Online – PowerShell 4.0 • Which version am I running? – $PSVersionTable #devconnections
  6. 6. POWERSHELL TIPS & TRICKS FOR EXCHANGE PowerShell basics • Verbs and Nouns – Get-, Set-, New-, Enable-, Remove- – Mailbox, DistributionGroup, ExchangeServer etc. • Works with objects which are loaded in memory • Processed/Manipulated in Memory – This can be very inefficient when not properly executed! #devconnections
  7. 7. POWERSHELL TIPS & TRICKS FOR EXCHANGE Connecting with PowerShell • Implicit Remoting $ExchSession= New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchange.contoso.com/PowerShell -Authentication Kerberos Import-PSSession $ExchSession • EXO: Uri https://ps.outlook.com/powershell/, Basic auth & AllowRedirection • Use -Prefix to import cmdlets as Verb-PrefixNoun, e.g. Get-CloudMailbox • Watch for serialization issues (everything's returned as a string) #devconnections
  8. 8. POWERSHELL TIPS & TRICKS FOR EXCHANGE How not to connect .. Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010  Unsupported  Bypasses RBAC #devconnections
  9. 9. POWERSHELL TIPS & TRICKS FOR EXCHANGE Objects and Properties • Select returns (Exchange) properties Get-Mailbox | Select Name • To read (multivalue) properties Get-Mailbox | Select Name, EmailAddresses Get-Mailbox | Select Name –ExpandProperty EmailAddresses Get-Mailbox | Select Name, @{n='EmailAddresses'; e={$_.EmailAddresses –join ","}} #devconnections
  10. 10. POWERSHELL TIPS & TRICKS FOR EXCHANGE Filtering • Get-Mailbox | Where {..} – Where command processes result set = inefficient • Get-Mailbox –Filter { .. } – Filter early when possible (depends on cmdlet) – Less data through pipe = efficient – AD admins  #devconnections
  11. 11. POWERSHELL TIPS & TRICKS FOR EXCHANGE Change multivalue properties • To change a multivalue property $addr= (Get-Mailbox User ).EmailAddresses $addr+= 'new@contoso.com' Set-Mailbox User - EmailAddresses $addr • This is more efficient: Set-Mailbox User –EmailAddresses @{Add='new@contoso.com';Remove='old@contoso.com'} • Only certain cmdlets, e.g. not Connector's IPranges #devconnections
  12. 12. POWERSHELL TIPS & TRICKS FOR EXCHANGE Fan Out improves efficiency • Fan Out distributes PowerShell commands Get-TransportServer | Get-MessageTrackingLog versus Get-TransportServer | ForEach { Invoke-Command -ConfigurationName Microsoft.Exchange -ConnectionUri http://$($_.Name)/PowerShell -ScriptBlock { Get-MessageTrackingLog } –Authentication Kerberos} • Complex or interactive ? => jobs / runspaces #devconnections
  13. 13. POWERSHELL TIPS & TRICKS FOR EXCHANGE Check Permissions • How to check permissions on Mailboxes Get-Mailbox | Get-MailboxPermission Get-Mailbox | Get-RecipientPermission #devconnections
  14. 14. POWERSHELL TIPS & TRICKS FOR EXCHANGE Check Permissions • Get more in detail Get-Mailbox | Get-MailboxPermission | Where { !$_.IsInherited –and $_.User –notlike 'NT AUTHORITYSELF' –and $_.AccessRights –eq 'FullAccess' } Get-RecipientPermission | Where { @('NT AUTHORITYSELF','NULL SID') -notcontains $_.Trustee} #devconnections
  15. 15. POWERSHELL TIPS & TRICKS FOR EXCHANGE Date Math • Get-Date • (Get-Culture).DateTimeFormat • Calculations (Get-Date).AddDays(-7) Get-Date (Get-Date).AddMonths(-1).ToString("yyyy/MM/01") (Get-Date (Get-Date).ToString(“yyyy/MM/01”)).AddDays(-1) • Use this for reporting, troubleshooting or scripting #devconnections
  16. 16. POWERSHELL TIPS & TRICKS FOR EXCHANGE Message Tracking • How does this come together? Get-MessageTrackingLog -Start (Get-Date).AddDays(-7) #devconnections
  17. 17. POWERSHELL TIPS & TRICKS FOR EXCHANGE Message Tracking • How does this come together? Get-MessageTrackingLog -Start (Get-Date).AddDays(-7) -EventId Send | Where { $_.Sender –like '*@contoso.com'} #devconnections
  18. 18. POWERSHELL TIPS & TRICKS FOR EXCHANGE Message Tracking • How does this come together? Get-MessageTrackingLog -Start (Get-Date).AddDays(-7) -EventId Send | Where { $_.Sender –like '*@contoso.com'} | Group Sender #devconnections
  19. 19. POWERSHELL TIPS & TRICKS FOR EXCHANGE Message Tracking • How does this come together? Get-MessageTrackingLog -Start (Get-Date).AddDays(-7) -EventId Send | Where { $_.Sender –like '*@contoso.com'} | Group Sender | Select Name,@{n='Total';e={ ($_.Group | Measure TotalBytes -Sum).Sum }} #devconnections
  20. 20. POWERSHELL TIPS & TRICKS FOR EXCHANGE Message Tracking • How does this come together? Get-MessageTrackingLog -Start (Get-Date).AddDays(-7) -EventId Send | Where { $_.Sender –like '*@contoso.com'} | Group Sender | Select Name,@{n='Total';e={ ($_.Group | Measure TotalBytes -Sum).Sum }} | Sort Total –Desc #devconnections
  21. 21. POWERSHELL TIPS & TRICKS FOR EXCHANGE Message Tracking • How does this come together? Get-MessageTrackingLog -Start (Get-Date).AddDays(-7) -EventId Send | Where { $_.Sender –like '*@contoso.com'} | Group Sender | Select Name,@{n='Total';e={ ($_.Group | Measure TotalBytes -Sum).Sum }} | Sort Total –Desc | Select –First 10 #devconnections
  22. 22. POWERSHELL TIPS & TRICKS FOR EXCHANGE #devconnections
  23. 23. POWERSHELL TIPS & TRICKS FOR EXCHANGE POWERSHELL SCRIPTING #devconnections
  24. 24. POWERSHELL TIPS & TRICKS FOR EXCHANGE Who uses scripting now? • Batchfiles • Windows Scripting Host • Kixtart • PowerShell • Other .. #devconnections
  25. 25. POWERSHELL TIPS & TRICKS FOR EXCHANGE • Arrays: , @() • Quotes: "$var" –ne '$var' • Escaping (`), e.g. "[`"n`"]" • "$(expression)", e.g. "$($_.Property)" • Aliases (? % gcm dir where ..) • $Profile (~ *nix .profile) • ResultSize 1000 • Out-GridView #devconnections
  26. 26. POWERSHELL TIPS & TRICKS FOR EXCHANGE Regular Expressions • Pattern matching / replacing • -match & -replace – Default case-insensitive – Use explicit operator: -cmatch, -imatch, .. – Returns $matches • More control? – [regexp]::match / [regexp]::replace #devconnections
  27. 27. POWERSHELL TIPS & TRICKS FOR EXCHANGE Examples $ip –match "d.d.d.d" $ip –match "d{1,3}.d{1,3}.d{1,3}.d{1,3}" $ip –match "(d{1,3}.){3}d{1,3}" $email –match "[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]+" "first last" -ireplace "([a-z]+)s([a-z]+)",'$2 $1' • Library: http://www.regexlib.com #devconnections
  28. 28. POWERSHELL TIPS & TRICKS FOR EXCHANGE Error Handling • Terminating / Non-Terminating – Control: -ErrorAction / $ErrorActionPreference • Try {} Catch {} Finalize {} Try { Set-Mailbox Dave –MaxMessageSize 100MB –EA Stop } Catch { Write-Error "Error: $($_.Exception.Message)" } Finally { Write-Output "We're done". } #devconnections
  29. 29. POWERSHELL TIPS & TRICKS FOR EXCHANGE Cmdlet Extension Agents • Since Ex2010 (N/A @ Edge) Get-CmdletExtensionAgent | ft Name,Priority,Enabled • Scripting Agent Extend, modify or replace non-Get cmdlet functionality Enable-CmdletExtensionAgent 'Scripting Agent' • ScriptingAgentConfig.xml Distribute @ All Exchange servers (script PushScriptingAgentConfig) Safeguard (code injection) Correct XML (case-sensitive tags, &=&amp; <=&lt; >=&gt; ) #devconnections PushScriptingAgentConfig.ps1
  30. 30. POWERSHELL TIPS & TRICKS FOR EXCHANGE Scripting Agent ApiCalls #devconnections Provision Default Properties •Default properties •Not overwrite values set by higher prio agent Update Affected IConfigurable •Pre-validation values Validate •Property Validation •Return $null = OK OnComplete •Post-Processing
  31. 31. POWERSHELL TIPS & TRICKS FOR EXCHANGE Anatomy #devconnections <?xml version="1.0" encoding="utf-8" ?> <Configuration version="1.0"> <Feature Name="MbxPostCfg" Cmdlets="New-Mailbox"> <ApiCall Name="OnComplete"> if($succeeded) { $Name = $provisioningHandler.UserSpecifiedParameters[“Name"] Set-CASMailbox –Identity $Name -ActiveSyncEnabled $false } </ApiCall> </Feature> </Configuration> Label Cmdlet(s) When Scriptblock
  32. 32. POWERSHELL TIPS & TRICKS FOR EXCHANGE #devconnections
  33. 33. POWERSHELL TIPS & TRICKS FOR EXCHANGE Take aways • Don't assume – .. everything works / is available / etc. – .. PowerShell is consistent • Filter early to improve efficiency • Test – incl. stuff you d/l & copy/paste one-liners – Use the WhatIf switch  #devconnections
  34. 34. POWERSHELL TIPS & TRICKS FOR EXCHANGE Links • Cmdlet Extension Agents – http://wp.me/pIJRx-vZ – http://bit.ly/PushScriptingAgentConfig • Extending ISE – http://wp.me/pIJRx-Kr • Fan-Out using jobs / runspaces – http://bit.ly/ExRunspace #devconnections
  35. 35. SESSION TITLE #devconnections Rate This Session Now! Rate with Mobile App: 1. Select the session from the Agenda or Speakers menus 2. Select the Actions tab 3. Click Rate Session Rate Using Our Website: 1. Register at www.devconnections.com/logintoratesession 2. Go to www.devconnections.com/ratesession 3. Select this session from the list and rate it Tell Us What You Thought of This Session Be Entered to WINPrizes!

×