27 November 2018

PowerShell One liners (continuous work in progress)

If you know a nice one liner that should be on here drop me a line.
Install the latest PowerShellGet version:
Install-Module PowerShellGet -Force
Find the number of users that connect through OWA:
"C:\Program Files (x86)\Log Parser 2.2\logparser.exe" "SELECT cs-username, Count(*) AS OWAHits from \\sr-xxxxx\d$\IISLogs\W3SVC1\u_ex*.log
 WHERE cs-uri-stem LIKE '/OWA/' AND cs-username IS NOT NULL GROUP BY cs-username ORDER BY OWAHits Desc" -rtp:-1
Find all soft deleted mailboxes
Get-MailboxDatabase | Get-MailboxStatistics | Where { $_.DisconnectReason -eq "SoftDeleted" } | Format-Table DisplayName,Database,DisconnectDate
Permanently delete soft deleted mailboxes
Remove-StoreMailbox -Database MBX02 -Identity "John Doe" -MailboxState SoftDeleted
Delete all soft deleted mailboxes per database
Get-MailboxStatistics -Database MBX02 | where {$_.DisconnectReason -eq "SoftDeleted"} | ForEach
 {Remove-StoreMailbox -Database $_.Database -Identity $_.MailboxGuid -MailboxState SoftDeleted}
Update the Offline Addressbook and the Global Addressbook
Get-OfflineAddressBook | Update-OfflineAddressBook
Get-GlobalAddressList | Update-GlobalAddressList
Update Windows Defender manually:
"%programfiles%\windows defender\mpcmdrun.exe" -signatureupdate -http
Search for IMAP enabled mailboxes:
Get-CASMailbox -ResultSize unlimited | where {$_.ImapEnabled -eq $true} | FL name | out-file C:\temp\imapenabled.txt
Enable Remote Desktop locally:
Set-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server' -Name fDenyTSConnections -Value 1
Or including the firewall rule:
(Get-WmiObject Win32_TerminalServiceSetting -Namespace root\cimv2\TerminalServices).SetAllowTsConnections(1,1) | Out-Null
(Get-WmiObject -Class "Win32_TSGeneralSetting" -Namespace root\cimv2\TerminalServices 
-Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0) | Out-Null
Get-NetFirewallRule -DisplayName "Remote Desktop*" | Set-NetFirewallRule -enabled true
Add a user to blocked senders
Set-MailboxJunkEmailConfiguration -Identity "UserName" –BlockedSendersandDomains @{Add="somebody@domain.com"}
Check if set correctly
Get-MailboxJunkEmailConfiguration -Identity "UserName" | FL BlockedSendersandDomains
To Remove a user from blocked senders
Set-MailboxJunkEmailConfiguration -Identity "UserName" –BlockedSendersandDomains @{Remove="somebody@domain.com"}
Delete the file "desktop.ini" from 2 directories deep:
get-childitem -path \\domain.lan\sharename\users\home\*\* -force -filter "desktop.ini" | foreach ($_) {remove-item $_.fullname -force 
-verbose 4>> c:\temp\desktopiniresults.txt}
Set UPN to match Mail Address for Office365 use:
Get-User -OrganizationalUnit "domain.com/OUName" -ResultSize unlimited | Where { -Not [string]::IsNullOrEmpty($_.WindowsEmailAddress) } | 
ForEach { Set-User -Identity $_.Guid.ToString() -UserPrincipalName $_.WindowsEmailAddress.ToString() }
Allow Windows 10 PC in workgroup to manage Hyper-v server:
winrm quickconfig -force
winrm set winrm/config/client ‘@{TrustedHosts=”Name of the Server”}’
Enable protocol logging for IMAP
Set-ImapSettings -Server "CAS01" -ProtocolLogEnabled $true
Disable protocol logging for IMAP
Set-ImapSettings -Server "CAS01" -ProtocolLogEnabled $false
Recreate the Sharedwebconfig.config files for Exchange 2013:
cd %ExchangeInstallPath%\bin
DependentAssemblyGenerator.exe -exchangePath "%ExchangeInstallPath%bin" -exchangePath "%ExchangeInstallPath%ClientAccess" 
-configFile "%ExchangeInstallPath%ClientAccess\SharedWebConfig.config"
DependentAssemblyGenerator.exe -exchangePath "%ExchangeInstallPath%bin" -exchangePath "%ExchangeInstallPath%FrontEnd\HttpProxy" 
-configFile "%ExchangeInstallPath%FrontEnd\HttpProxy\SharedWebConfig.config"
Get the list of network profiles on the system.
Change the network interface to private, use the network interface index number from the previous command.
Set-NetConnectionProfile -InterfaceIndex 10 -NetworkCategory Private
Get Exchange build number:
Get-ExchangeServer | Format-List Name, Edition, AdminDisplayVersion
Get Exchange Schema version:
"Exchange Schema Version = " + ([ADSI]("LDAP://CN=ms-Exch-Schema-Version-Pt," + ([ADSI]"LDAP://RootDSE").schemaNamingContext)).rangeUpper
Set Default Addressbook Policy and Retention Policy for all mailboxes at once:
Get-Mailbox -ResultSize unlimited | Set-mailbox -AddressBookPolicy "Your AddressBookPolicy" -RetentionPolicy "Your - Default Policy"
Quickly add the Exchange PowerShell module to a regular PowerShell console:
Add-PSSnapin *exchange*
Add multiple aliasses at once:
Set-Mailbox "UserName" -EmailAddresses @{add="UserName01@domain.com","UserName02@domain.com","UserName03@domain.com","UserName04@domain.com",
List all mailboxes that have a forwarding address
Get-mailbox -Resultsize Unlimited | select DisplayName,ForwardingAddress | where {$_.ForwardingAddress -ne $Null}
Send Output to Clipboard with PowerShell
Get-EventLog application -Newest 1 | clip
Find specific Help articles with Powershell
Get-Help about_
press tab to cycle through the matches
Find white space (Available new mailbox space) in all databases
Get-MailboxDatabase -Status | sort name | select name,@{Name='DB Size (Gb)';
Expression={$_.DatabaseSize.ToGb()}},@{Name='Available New Mbx Space Gb)';
Create Powershell profile
New-Item -path $profile -type file –force
Edit the newly created profile in the following location
Load all Powershell available modules at once:
Get-Module -ListAvailable | Import-Module
Turn off shutdown tracker for Windows server
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability"
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Reliability" -Name ShutdownReasonOn -Value 0
Combine multiple files into one;
Get-ChildItem -filter "c:\temp\*.html" | % { Get-Content $_ -ReadCount 0 | Add-Content "c:\temp\combined_files.html" }
Get-Content -path c:\temp\eventlogs\*.html | Add-Content -Path C:\temp\Eventlogs\combined.html
Get users with imap enabled:
Get-CASMailbox -ResultSize unlimited | Where-Object {$_.imapenabled -eq "true"} | fl name,imapenabled
Get empty AD groups and email the output;
$body=Get-ADGroup -Filter * -Properties Members | where {-not $_.members} | select Name
Send-MailMessage -smtpserver smtp.domain.lan -subject
 "Empty groups" -to "user1@domain.com,user2@domain.com" -from "user@domain.com" -Body ( $Body | out-string )
Set send on behalf of rights;
Set-Mailbox UserMailbox -GrantSendOnBehalfTo UserWhoSends
View who has which permissions on a user mailbox;

Get-MailboxFolderPermission -Identity "alias:\postvak in" | fl 
(for Dutch)

Get-MailboxFolderPermission -Identity "alias:\inbox" | fl 
(for English)

View who has which permissions on a user calendar;

Get-MailboxFolderPermission -Identity alias:\agenda | fl 
(for Dutch)
Get-MailboxFolderPermission -Identity alias:\calendar | fl 
(for English)

Remove user rights on a mailbox/folder for an other user:
Remove-MailboxFolderPermission -Identity username1:\agenda -User username2
Add user rights on a mailbox/folder for an other user:
Add-MailboxFolderPermission -Identity username1:\agenda -AccessRights Publishingeditor -User username2
MAPI encryption enabled or disabled; (for Outlook 2003 clients)

Get-RpcClientAccess | fl encryp*,server
View blocked ActiveSync devices, in "Blocked" state for longer than a month;

Get-ActiveSync Device | Where {$_.DeviceAccessState -eq "blocked"} | Select DeviceModel | ft -auto
Delete "Blocked" activesync devices, in "Blocked" state for longer than a month;

Get-ActiveSync Device | Where {$_.DeviceAccessState -eq "Quarantined" -and $_.FirstSyncTime
 -lt (Get-Date).AddMonths(-1)} | Remove-ActiveSyncDevice

Delete all ActiveSync devices with DeviceAccessState "Blocked";

Get-ActiveSyncDevice | Where {$_.DeviceAccessState -eq "Blocked"} | 

To retrieve all Exchange-related events:

Get-EventLog Application | Where { $_.Source -Ilike “*Exchange*” } 

07 November 2018

Unable to remove shared mailbox from Outlook profile

As a postmaster or Exchange admin you periodically need to open other users mailboxes to move stuff, restore stuff, add or adjust stuff and so on.

After a while you have a long list of attached mailboxes that you don't need anymore.
And sometimes those mailboxes won't disconnect properly.

How do you get rid of them when the mailboxes are still listed in your folder panel though the mailbox but not listed in Account Settings/Change/More settings/Advanced?

You can view the following attribute in ADUC:

Search for the (shared) mailbox you want to remove, right-click the (shared) mailbox, in the Attribute Editor, double click the msExchDelegateListLink attribute, check if your account is listed there. You can remove your account from the msExchDelegateListLink attribute to clear Automapping.
Restart Outlook and check if the shared mailbox is removed.