Find-EmailAddress.psm1
function Find-EmailAddress{ <# .SYNOPSIS Find-EmailAddress .DESCRIPTION Find-EmailAddress in Exchange On-Prem or Online .EXAMPLE Find-EmailAddress PartOrAll@EmailAddress.com .NOTES Authors : Simon Godefroy - Simon.Godefroy@FocusedIT.co.uk Version : 1.0.5 Date : 2023.05.23 Update : 1.0.5 SG - 2023.05.23 First Published Version Update : 1.0.4 SG - 2023.05.23 Updated error handling for conflicting and no sessions found Update : 1.0.3 SG - 2023.03.10 Updated to support ExchangeOnlineManagement v3 Module Update : 1.0.2 SG - 2021.12.23 Resolved issue where search string contains an apostrophe Update : 1.0.1 SG - 2021.13.20 Added -IgnoreDefaultScope to allow for multiple Exchange Servers Update : 1.0.0 SG - 2021.12.13 Initial Script .LINK http://www.FocusedIT.co.uk #> [CmdletBinding()] Param( #[Alias("","")] #[Parameter(Position=0,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$false)] [string]$EmailAddress #, #[Alias("","")] #[Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$false)] #[switch]$Switch #, ) begin{ $AllSessions = Get-PSSession $ExchangeSession = $AllSessions |?{$_.ConfigurationName -like "Microsoft.Exchange"} if(gcm Get-ConnectionInformation){ $ExchangeOnlineSession = (Get-ConnectionInformation).State } try{ if((!($ExchangeOnlineSession)) -and (!($ExchangeSession))){ throw "Exchange Session not detected - connect to On-prem or Online Exchange" }elseif($ExchangeOnlineSession -and $ExchangeSession){ throw "Conflicting sessions detected - please restart PowerShell and make a connection" } }catch{ Write-Error $Global:Error[0] -ErrorAction Stop } $Objects = @() if($ExchangeSession | ?{$_.ComputerName -like "*$($ENV:USERDNSDOMAIN)*"}){ $OnPrem = $true Write-Host "On-Prem Exchange detected" }else{ $OnPrem = $false Write-Host "Exchange Online detected" } } process{ if($EmailAddress -like "*'*"){ $EmailAddress = $EmailAddress -replace "'","''" } if($OnPrem){ $Objects += Get-Recipient -Filter "EmailAddresses -like '*$EmailAddress*'" -IgnoreDefaultScope }else{ $Objects += Get-Recipient -Filter "EmailAddresses -like '*$EmailAddress*'" } } end{ $Objects | Select Name,RecipientType,RecipientTypeDetails,EmailAddresses } } |