Saturday 10 October 2020

Saturday 11 July 2020

Office 365 Distribution Group Report


param(
[Parameter(Position=0)]
[DateTime]$StartDate,
[DateTime]$EndDate
)

$DistGroups = Get-DistributionGroup -ResultSize Unlimited
$EndDate = Get-Date
$StartDate = $EndDate.AddDays(-10)
$Output=[System.Collections.ArrayList]@()
$Output.Clear()

foreach($DL in $DistGroups){
    $Val=Get-Messagetrace -RecipientAddress $DL.PrimarySMTPAddress -StartDate $StartDate -enddate $EndDate
    $Mem = (Get-DistributionGroupMember -Identity $DL.PrimarySMTPAddress).count
    $LastEmailReceivedOn = (Get-MessageTrace -RecipientAddress $DL.PrimarySMTPAddress|Select Received -last 1).Received

        If($Val.Count-ne0)
        {
            $Property=[pscustomobject][ordered]@{
                Status="Active"
                Owner=$dl.ManagedBy
                GroupName=$DL.DisplayName
                EmailAddress=$DL.PrimarySMTPAddress
                EmailCount=$Val.Count
                #Member=$Mem
                LastEmailReceivedOn=$LastEmailReceivedOn
            }
            $Output.Add($Property)
        }
        else
        {
            $Property=[pscustomobject][ordered]@{
                Status="InActive"
                Owner=$dl.ManagedBy
                GroupName=$DL.DisplayName
                EmailAddress=$DL.PrimarySMTPAddress
                EmailCount=$Val.Count
                #Member=$Mem
                LastEmailReceivedOn=$LastEmailReceivedOn
            }
            $Output.Add($Property)
        }
}
$Output|sort Status|ft -AutoSize


Sunday 28 June 2020

Progress Bar



for($i=900;$i-ge1;$i--)
    {
        Write-Progress -Activity "Running Azur AD Sync..." -SecondsRemaining $i -PercentComplete (($i/900)*100)
        Start-Sleep -Seconds 1
    }

    for($i=1;$i-le900;$i++)
    {
        Write-Progress -Activity "Azur AD Sync" -Status "Running..." -SecondsRemaining $i -PercentComplete (($i/900)*100)
        Start-Sleep -Seconds 1
    }




Wednesday 27 May 2020

Get Mailbox Total Size


((Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics).TotalItemSize.Value.ToMB() | `
Measure-Object -Sum).Sum




Monday 25 May 2020

Last Email Sent/Received Report - Exchange On-prem

#Last Email Received Report
========================

$Mailboxes = Get-Mailbox -RecipientTypeDetails UserMailbox,SharedMailbox
$Output=$null
$Output=[System.collections.Arraylist]@()
$Mailboxes|ForEach{
    $Property=[pscustomobject]@{
        Name = $_.Name
        LastEmailReceivedOn = (Get-MessageTrackingLog -EventId "Receive" -Recipients $_.UserprincipalName|Select TimeStamp -last 1).TimeStamp
    }
    $Output.Add($Property)
}
$Output

#$Output|?{$_.LastEmailReceivedOn -ne $null}|sort LastEmailReceivedOn



#Last Email Sent Report
========================

$Mailboxes = Get-Mailbox -RecipientTypeDetails UserMailbox,SharedMailbox
$Output=$null
$Output=[System.collections.Arraylist]@()
$Mailboxes|ForEach{
    $Property=[pscustomobject]@{
        Name = $_.Name
        LastEmailSentOn = (Get-MessageTrackingLog -EventId "Send"-Sender $_.UserprincipalName|Select TimeStamp -last 1).TimeStamp
    }
    $Output.Add($Property)
}

$Output


Wednesday 29 April 2020

Last Logon Date



Get-ADUser <samAccountName> -Properties * | fl Enabled,SamAccountName,Name,@{n="LastLogon";e={[datetime]::FromFileTime($_.lastLogon)}}


Get-ADUser -Filter * -Properties Enabled,SamAccountName,Name,LastLogon| `
Where {([datetime]::FromFileTime($_.lastLogon) -lt (Get-Date).AddDays(-90))} | `
Select Enabled,SamAccountName,Name,@{n="LastLogon";e={[datetime]::FromFileTime($_.lastLogon)}}






Tuesday 10 March 2020

Getting License and Mailbox Size Report



#Connect to EXO and MSOL

#Provide UPN as Input
$Upn= Import-Csv "CSV Path"

$out=$null
$out=[System.Collections.ArrayList]@()
Foreach($u in $Upn)
{
    $data = Get-MailboxStatistics $u|Select DisplayName,TotalItemSize #@{n='TotalItemSize';e={(($_.totalitemsize) -split '[(]')[0]}}

    $Property=[pscustomobject]@{
        DisplayName = $data.DisplayName
        UserprincipalName = $u
        License = ((Get-MsolUser -UserPrincipalName $u).Licenses|?{$_.AccountSkuId -match "ENTERPRISEPACK"}).AccountSkuId
        TotalSize = $data.TotalItemSize
     }
    $Out.Add($Property)
    $Property | Export-Csv D:\lalit.csv -Append -NoTypeInformation
 
}
$out






Saturday 25 January 2020

Exchange On-prem Snap-In for PowerShell


Exchange 2007

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin;


Exchange 2010

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010;



Exchange 2013 & 2016

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn;






Monday 20 January 2020

Generate Random Password


Method 1

$Password = 'ABCDEFGHKLMNOPRSTUVWXYZ'
$Password += 'abcdefghiklmnoprstuvwxyz'
$Password += '1234567890'
$Password += '!"§$%&/()=?}][{@#*+'

Get-RandomCharacters -length 7 -characters $Password


Method 2

$P1= 'ABCDEFGHKLMNOPRSTUVWXYZ'
$P2 = 'abcdefghiklmnoprstuvwxyz'
$P3 = '1234567890'
$P4 = '!"§$%&/()=?}][{@#*+'
$P5= 'ABCDEFGHKLMNOPRSTUVWXYZ'
$P6 = '1234567890'

$Result=[System.Collections.ArrayList]@()
for($i=1;$i-le1500;$i++)
{
$op=$null
$op+=$p1[(Get-Random -Minimum 1 -Maximum $p1.Length)]
$op+=$p2[(Get-Random -Minimum 1 -Maximum $p2.Length)]
$op+=$p3[(Get-Random -Minimum 1 -Maximum $p3.Length)]
$op+=$p4[(Get-Random -Minimum 1 -Maximum $p4.Length)]
$op+=$p5[(Get-Random -Minimum 1 -Maximum $p5.Length)]
$op+=$p6[(Get-Random -Minimum 1 -Maximum $p6.Length)]
$Result.add($op)
}
$Result | select -Unique



Saturday 18 January 2020

Array List - Example Fetching Mailbox Permission

Declare Array List

Method 1:
[System.Collections.ArrayList]$ArrayList = @() 

Method 2:
$ArrayList = [System.Collections.ArrayList]@() 

Method 3:
$ArrayList = [System.Collections.ArrayList]::new() 

Method 4:
$ArrayList = New-Object System.Collections.ArrayList($Null) 

Method 5:
$ArrayList = New-Object System.Collections.ArrayList(,(1..10)) 

Method 6:
$ArrayList = New-Object System.Collections.ArrayList


Mailbox Permission

$upn = (Get-Mailbox -RecipientTypeDetails usermailbox)

$out = $null
$out=[System.Collections.ArrayList]@()
Foreach($u in $UPN)
{
    $data = Get-MailboxPermission $u.userprincipalname |select User,AccessRights

    @($data).ForEach({
    $property= [ordered]@{
    'DisplayName' = $u.DisplayName
    'AccessRights' = $_.AccessRights
    'User' = $_.User
    }
    $obj = New-Object psobject -Property $property

#Adding values to Array List
    $out.Add($obj)
    })
}
$out

Friday 17 January 2020

Prevent Users From Deleting Emails From A Shared Mailbox

PowerShell Steps


Create a test shared mailbox SharedMailbox@domain.com
Create a Security group SecurityGroup@domain.com Provided access to few users
Provide access to mailbox root and inbox folder
  • Add-o365MailboxFolderPermission SharedMailbox@domain.com -AccessRights Reviewer -User SecurityGroup@domain.com
  • Add-o365MailboxFolderPermission SharedMailbox@domain.com:\inbox -AccessRights Reviewer -User SecurityGroup@domain.com
Add the shared mailbox on outlook



Manual Steps

To let users only review emails but unable to edit/remove emails in shared mailbox, you can setup the shared mailbox by following the steps below,

1 - Remove the user from the group which has been granted the full access permission on the shared mailbox,
2 - Open the shared mailbox in Outlook with another account who has full access permission on the shared mailbox,
3 - Right click the shared mailbox, click Data File Properties, in Permission tab, click add to add a user, and choose reviewer from the Permission level drop down list,
4 - Right click the inbox folder of the shared mailbox, click Properties, in Permission tab, click add to add the same user, and choose reviewer from the Permission level drop down list,

Then this user can open the shared mailbox in Outlook as usual but only able to view the emails in inbox and unable to edit/remove emails.

Sunday 5 January 2020

Send Error report on Email


try
{
 It will generate error
}

catch
{
    Write-host $_.Exception.Message -ForegroundColor Yellow
    Write-host $_.Exception.ItemName -ForegroundColor Green
    $ErrorMessage = $_.Exception.Message
    $FailedItem = $_.Exception.ItemName
    $cred = Get-Credential
    Send-MailMessage -From Sender@domain.com -To Recipient@domain.com -Subject "Script Failed!" -SmtpServer smtp.office365.com -Body "We failed to read file $FailedItem. The error message was $ErrorMessage" -Port 587 -Credential $cred -BodyAsHtml -UseSsl
    Continue
}





Show Progress bar



  For ($i=0;$i -lt 10; $i++)
  {

  $percentComplete = ($i / 10) * 100

  Write-Progress -Activity 'Running..' -Status "Did thing $i  times" -PercentComplete $percentComplete

  sleep 1
   }



Saturday 4 January 2020

Unzip Files with PowerShell


Add-Type -AssemblyName System.IO.Compression.FileSystem

Param(

  [Parameter(Mandatory=$True)]
  [String]$ZipFile,

  [Parameter(Mandatory=$True)]
  [String]$OutPath

)

Function Unzip
{
       [System.IO.Compression.ZipFile]::ExtractToDirectory($ZipFile, $OutPath)
}

Unzip -ZipFile "C:\Users\sumant\Downloads\PDFXVE8.zip" -OutPath "C:\Users\sumant\Downloads\Test001"




PowerShell Speaks



Param(

[Parameter(Mandatory = $True)]
[String]$Text

)

Function Voice-Output($Speak)
{
Add-Type -AssemblyName System.speech
$Say = New-Object System.Speech.Synthesis.SpeechSynthesizer
$Say.Speak($Speak)
}

$Text = Read-Host "Enter Text"

Voice-Output -Speak $Text



Friday 3 January 2020

Remove AD Groups from Disabled Users


 Param(
 [Parameter (Mandatory=$False)]$DisabledUser,
 [Parameter (Mandatory=$False)]$Group,
 [Parameter (Mandatory=$False)]$Properties,
 [Parameter (Mandatory=$False)]$ErrorProperties,
 [Parameter (Mandatory=$False)]$ObjCompleted,
 [Parameter (Mandatory=$False)]$ObjError
 )

 <# Details of Property : msExchRecipientTypeDetails
 "1" User Mailbox
 "4" Onprem Shared
"16" Onprem Room
"128" MailUser
"2147483648" User Mailbox Converted to Shared Mailbox
"8589934592" Cloud Room
"34359738368" Cloud Shared Mailbox
"8388608" System Mailbox
"4398046511104" System Mailbox
#>

$DisabledUser = (Get-ADUser -Filter * -Properties Name,SamAccountName,Enabled,UserprincipalName,msExchRecipientTypeDetails |`
?{($_.Enabled -match 'false')`
-And (($_.samAccountName).StartsWith("i"))`
-And ($_.msExchRecipientTypeDetails -ne "4")`
-And ($_.msExchRecipientTypeDetails -ne "16")`
-And ($_.msExchRecipientTypeDetails -ne "2147483648")`
-And ($_.msExchRecipientTypeDetails -ne "8589934592")`
-And ($_.msExchRecipientTypeDetails -ne "34359738368")`
-And ($_.msExchRecipientTypeDetails -ne "8388608")`
-And ($_.msExchRecipientTypeDetails -ne "4398046511104")
})|Select Name,SamAccountName,Enabled,UserprincipalName,msExchRecipientTypeDetails

Foreach($User in $DisabledUser)
{
    $Group = (Get-ADPrincipalGroupMembership $User.samAccountName).name |?{$_ -ne "Domain Users"}
   
    Write-host "`n"
    Write-host "UserprincipalName:" $User.UserprincipalName
    Write-host "**************************************************"
 
    Foreach($g in $Group)
    {
            try{
                Remove-ADGroupMember -Identity $g -Members $user.SamAccountName -Confirm:$false -ErrorAction Stop
                Write-host "Removing User:"$user.SamAccountName -NoNewline
                Write-Host "`t" -NoNewline
                Write-Host "from Group:"$g
             
                $Properties=@{
                   'Task' = "Removed"
                   'User' = $user.SamAccountName
                   'Group' = $g
                   }
                $ObjCompleted = New-Object PSObject -Property $Properties
                $ObjCompleted  |export-csv C:\SUMANT\RemoveGroupfromDisabledUsers\Completed.csv -Append -NoTypeInformation

               }
     
            Catch{
                   $ErrorProperties=@{
                   'User' = $user.SamAccountName
                   'Group' = $g
                   'Error Log'= $_
                 }
                $ObjError = New-Object PSObject -Property $ErrorProperties
                $ObjError |export-csv C:\SUMANT\RemoveGroupfromDisabledUsers\Errors.csv -Append -NoTypeInformation
        }
    }
}



Non MFA Script based GUI Tool to Manage Office 365 Exchange Online