Sunday, November 10, 2013

Shell Script Microsoft Exchange server 2010



ForEach ($mailbox in $mailbox) {Enable-Mailbox -Identity $Mailbox.Identity -Database $Mailbox.Database}

SAVE THIS AS C:\ENABLEBOX.PS1
NEXT: Run the Script
Go to Exchange Management Shell
You can change the directory to the root by typing cd\ then hit Enter (NOTE: If you just typed the words "then hit Enter" you do not belong working on servers)

Then type: ./enablebox.ps1

Just in case you want to enable archive for all users in the csv add this to the above script. 
Add <| Enable-Mailbox –Archive -ArchiveDatabase "<enter archive db name here>"}> Shown below in its entirety. 

$mailbox=import-csv C:\<filename>.CSV
ForEach ($mailbox in $mailbox) {Enable-Mailbox -Identity $Mailbox.Identity -Database $Mailbox.Database | Enable-Mailbox –Archive -ArchiveDatabase "<enter archive db name here>"}



Reference : Mailbox Script



Please check this command >Get-Mailbox | Where {$_.ProhibitSendReceiveQuota -gt 100}

Value 100 is in bytes to convert MB into Bytes for example, you need to convert 500 MB into bytes for Shell, then multiply MB by 1048576

5000 MB x 1048576 = 5242880000  bytes

So the command would be Get-Mailbox | Where {$_.ProhibitSendReceiveQuota -gt 5242880000}


Similarly you can change object from Mailbox to Mailboxdatabase



--------------------------------------------------------------------------------
Get-MailboxDatabase | Select-Object Name,IssueWarningQuota,ProhibitSendQuota,ProhibitSendReceiveQuota | Sort-Object Name | Export-Csv –Path .\DatabaseLimits.csv –NoTypeInformation
Get-Mailbox | Select-Object DisplayName,Database,IssueWarningQuota,ProhibitSendQuota,ProhibitSendReceiveQuota | Sort-Object DisplayName | Export-Csv –Path .\MailboxLimits.csv –NoTypeInformation

http://help.outlook.com/en-us/140/Gg576861(d=lightweight).aspx
--------------------------------------------------------------------------------


--------------------------------------------------------------------------------
To get a list of all users on an Exchange 2010 server who are Unified messaging-enabled

 $Mailboxes = Get-Mailbox
 $Mailboxes = | ForEach { If($_.UmEnabled -Eq $True){$_.Name}}
--------------------------------------------------------------------------------


--------------------------------------------------------------------------------
 script that will monitor the index state.

Get-mailboxdatabase | Get-MailboxDatabaseCopyStatus | where {$_.contentindexstate -ne "Healthy" -and $_.contentindexstate -ne "Crawling"} | select Name,DatabaseName,Status,ContentIndexState,MailboxServer,ActiveDatabaseCopy,ActivationSuspended
--------------------------------------------------------------------------------


ShowInlineAttachments
===============================================
We run the set-OrganizationConfig -ShowInlineAttachments:$true

ThrottlingPolicy
===============================================
Get-ThrottlingPolicy | Where-Object ($_.IsDefault -eq “True”) | FL Identity



ExTrace.exe (This is Microsoft proprietary tool and need to contact Microsoft)
===============================================
ExTrace.exe -v -c xx.etl >output.txt

NLTEST
===============================================
nltest /dsgetdc "owen.edu"
nltest /dsgetsite
nltest /securesite
netdom query dc
netdom query fsmo
nltest /sc_change_pwd:<DC FQDN>
//On W2k8 DC, nltest /sc_change_pwd:federation.local, will reset the password 

set u


Produce a list of Full Access Permissions
===============================================
For full access, from EMS run this command
get-mailbox | %{$foo = $_; Get-MailboxPermission $foo | ?{$_.AccessRights -eq "FullAccess" -and $_.IsInherited -eq $false}} | ft {$foo},User,AccessRights

get-mailbox | %{$mailbox = $_; Get-ADPermission $mailbox.DistinguishedName | ?{$_.ExtendedRights -like "Send-As" -and $_.User -notlike "NT AUTHORITY\SELF"}} | ft {$mailbox},user,{"Send-As"}

ADPLUS
=================================================
adplus.exe -crash -pn msexchangetransport.exe -NoDumpOnFirst -o e:\dumps 






Default Scipts found in Exchange 2010 scripts folder

ActiveSyncReport.ps1                                                     
AddReplicaToPFRecursive.ps1                                              
AddUsersToPFRecursive.ps1                                                
AggregatePFData.ps1                                                      
CheckDatabaseRedundancy.ps1                                               
CheckInvalidRecipients.ps1                                               
CITSConstants.ps1                                                         
CITSLibrary.ps1                                                          
CITSTypes.ps1                                                            
CollectOverMetrics.ps1                                                   
CollectReplicationMetrics.ps1                                            
Configure-SMBIPsec.ps1                                                   
ConfigureAdam.ps1                                                        
ConfigureNetworkProtocolParameters.ps1                                   
ConvertOABVDir.ps1                                                       
ConvertTo-MessageLatency.ps1                                             
DagCommonLibrary.ps1                                                     
DatabaseMaintSchedule.ps1                                                
DiagnosticScriptCommonLibrary.ps1                                         
Disable-InMemoryTracing.ps1                                              
enable-CrossForestConnector.ps1                                           
Enable-InMemoryTracing.ps1                                               
enable-OutlookCertificateAuthentication.ps1                               
ExchUCUtil.ps1                                                           
Export-OutlookClassification.ps1                                         
Export-RetentionTags.ps1                                                 
get-setuplog.ps1                                                         
Get-UCPool.ps1                                                           
GetDatabaseForSearchIndex.ps1                                            
GetSearchIndexForDatabase.ps1                                            
Import-RetentionTags.ps1                                                 
LargeToken-IIS_EWS.ps1                                                   
LargeToken-Kerberos.ps1                                                  
MailboxDatabaseReseedUsingSpares.ps1                                     
ManageScheduledTask.ps1                                                  
MigrateUMCustomPrompts.ps1                                                
Move-TransportDatabase.ps1                                               
MoveAllReplicas.ps1                                                      
MoveMailbox.ps1                                                          
new-TestCasConnectivityUser.ps1                                          
Prepare-MoveRequest.ps1                                                  
 RedistributeActiveDatabases.ps1                                          
Reenable-AuditLoggingAgent.ps1                                           
RemoveReplicaFromPFRecursive.ps1                                         
RemoveUserFromPFRecursive.ps1                                            
ReplaceReplicaOnPFRecursive.ps1                                          
ReplaceUserPermissionOnPFRecursive.ps1                                   
ReplaceUserWithUserOnPFRecursive.ps1                                     
ResetAttachmentFilterEntry.ps1                                           
ResetCasService.ps1                                                       
ResetSearchIndex.ps1                                                     
ResumeMailboxDatabaseCopy.ps1                                             
RollAlternateServiceAccountPassword.ps1                                  
StartDagServerMaintenance.ps1                                            
StopDagServerMaintenance.ps1                                             
StoreTSConstants.ps1                                                     
StoreTSLibrary.ps1                                                       
Troubleshoot-CI.ps1                                                      
Troubleshoot-DatabaseLatency.ps1                                         
Troubleshoot-DatabaseSpace.ps1     

Check Public Folder Permission

Get-PublicFolder "\" -Recurse | Get-PublicFolderClientPermission | Out-File -FilePath "c:\Temp\PFPerms.txt"

Event logging level BETWEEN SITES
===========================================
set-transportserver -identity <servername> - IntraOrgConnectorProtocolLoggingLevel verbose

set-transportserver -identity <servername> - IntraOrgConnectorProtocolLoggingLevel None

The logs are stored under the Logs folder of TransportRoles


How to find Mailbox is Shared Mailbox
C:\Get-mailbox -Resultsize unlimited | Where-object {$_.Isshared -eq $True}



An alternative way to identify possible problematic receive connectors by using Exchange Management Shell, is if the queue delivery type is SmtpRelayToRemoteAdSite. To do this, run the following shell commands:
$remotesite = (get-queue | where {$_.LastError -like "451 4.4.0*"}).NextHopDomain

get-exchangeserver | where {$_.site -like '*'+$remotesite} | get-transportserver | Get-ReceiveConnector | where {$_.Bindings -like '*:25*'} | where {$_.AuthMechanism -notlike '*Exchange*'

From blog 
http://blogs.technet.com/b/rmilne/archive/2014/02/23/exchange-2010-tip-of-the-day-26-to-50.aspx

This command spins through all your mailbox servers and reconnects all the uniquely identified but disconnected mailboxes in any one of the mailbox stores:
$Servers = Get-ExchangeServer 


$Servers | ` Where { $_.IsMailboxServer -Eq '$True' } ` | ForEach { Get-MailboxStatistics -Server $_.Name ` 

  | Where { $_.DisconnectDate -NotLike '' } ` | ForEach { Connect-Mailbox -Identity `$_.DisplayName -Database $_.DatabaseName} }


Want to know what version of Exchange Server each of your servers is running? Type:
Get-ExchangeServer | Format-Table Name, *Version*


Want to create a group of test users in your lab? Use this command:
1..100 | ForEach { Net User "User$_" MyPassword=01 /ADD /Domain; Enable-Mailbox "User$_" }


How to switch to Scripts folder in "Exchange Management Shell"
From EMS : type this command cd $exscripts



Find specific Event id in application log via Scripts
Get-EventLog "Application" | Where-Object {$_.EventID -eq 109} | Select-Object EventID,TimeGenerated,Message | Export-CSV -NoTypeInformation -Path c:\Search_StartEvents.csv


TEST-EXCHANGESEARCH //for checking the Content Index


Get-Mailbox -Database NA1-ERICNOR-1\ NA1-ERICNOR-1-SG1\ NA1-ERICNOR-1-DB1 | Test-ExchangeSearch | ft -a



Scripts to find how many users are logon using OWA 

Method 1: 
You can find the output when you run get-logonstatistics from the article below:
View Logon Statistics

Method 2:
Besides, you can use logparser to analyze it
C:\Program Files (x86)\Log Parser 2.2\logparser.exe" "SELECT TOP 10 cs-username, Count(*) AS OWAHits INTO OWAActivity.gif FROM C:\Inetpub\logs\LogFiles\W3SVC1\u_ex*.log WHERE cs-uri-stem LIKE '/OWA/' AND cs-username IS NOT NULL GROUP BY cs-username ORDER BY OWAHits DESC" -charttype:Bar3D -o:CHART -view:ON
Or:
"C:\Program Files (x86)\Log Parser 2.2\logparser.exe" "SELECT TO_STRING(time, 'HH') AS Hour, COUNT(*) AS Hits INTO hitPerSecond.jpg FROM C:\Inetpub\logs\LogFiles\W3SVC1\u_ex*.logGROUP BY Hour ORDER BY Hour ASC" -i:IISW3C -o:CHART -chartType:ColumnClustered -chartTitle:"Hourly Hits" -groupSize:420x280

Method 3:
We can run the command below to get the current number of outlook or OWA user who is connecting to Exchange Servers.
Get-Counter "\MSExchange RpcClientAccess\User Count" -ComputerName  name|ft
Get-Counter "\MSExchange OWA\Current Unique Users" -ComputerName  name |ft

OWA session with name of the user
========================================================
Get-Mailbox | Get-LogonStatistics | Where-Object {$_.ApplicationID -eq "Client=OWA"} | Select-Object UserName,LastAccessTime | ConvertTo-Html -Title "OWA actives sessions" -PostContent "<b>Thierry MILLE (c) 2011</b>" | Out-File C:\owa.htm; Send-MailMessage -From sender@domain.com -To recipient@domain.com -Subject "OWA sessions" -Attachments C:\owa.htm -SmtpServer 127.0.0.1; Remove-Item C:\owa.htm


How to delete and Export Mailbox without AVI MPEG files
========================================================
Get-Mailbox -ResultSize 'Unlimited' | Export-Mailbox -DeleteContent -AttachmentFilenames '*.avi', '*.mpeg' -TargetMailbox  ExportedMailbox -TargetFolder 'Export'

How to increase Logging level from Shell
========================================================
Get-EventLoglevel -server Servername

1.     Get-EventLogLevel MSExchangeTransport | set- EventLogLevel –level expert

Get-EventLogLevel MSExchangeTransport | Set-EventLogLevel -Level Expert (7) High (5) Lowest (0) Low (1)

Get-Eventloglevel msexchangetransport | set-Eventloglevel -level low

Set-Eventloglevel "MSExchangeMailSubmission\General" -level expert

Set-EventLogLevel “MSExchange POP3\General” -Level High

Set-EventLogLevel “MSExchange POP3\General” -Level lowest

set-transportserver -identity "servername" -IntraOrgConnectorProtocolLoggingLevel verbose

Set-EventLogLevel "Servername\MSExchangeSA\OAL Generator" -Level High
                                                  MSExchange IMAP4\General                                             
                                                  MSExchange POP3\General   

Set-eventloglevel -Identity ECIdParameter -Level Lowest | Low | Medium | High | Expert [CommonParameters]

Set-POPSettings -Server "HLBDEXCH" -protocolLogEnable $true

Set-EventLogLevel –identity "MSExchangeMailboxAssistants\Service" -Level Expert

Set-EventLogLevel –identity "MSExchangeMailboxAssistants\OOF Assistant" -Level Expert

Set-EventLogLevel –identity "MSExchangeMailboxAssistants\OOF Library" -Level Expert

Static domain controller
================================

Set-ExchangeServer –Identity (name of your Exchange Server goes here) –StaticDomainControllers $NULL


Pipelining Tracing
------------------------------
Run in the following order
1. Set-TransportServer <Identity> -PipelineTracingSenderAddress <SMTPAddress>     //from Sender
    Set-TransportServer <Identity> -PipelineTracingSenderAddress "<>"    // from servers

2. Set-TransportServer <Identity> -PipelineTracingPath <LocalFilePath>
    Set-TransportServer Server1 -PipelineTracingPath "C:\Pipeline Tracing Logs"

3. Set-TransportServer <Identity> -PipelineTracingEnabled <$True | $False>

    Set-TransportServer Server1 -PipelineTracingEnabled $True



Or single command sets all
Set-TransportServer –Identity “Hub Transport Server Name>” –PipelineTracingSenderAddress “Sender email address from one of the poison messages” –PipelineTracingPath “C:\Pipeline Tracing” –PipelineTracingEnabled $true –ContentConversionTracingEnabled $true

Disable Pipelining tracing
Set-TransportServer –Identity “Hub Transport Server Name” –PipelineTracingSenderAddress “Mail from Email Address in one of the message” –PipelineTracingPath “C:\Pipeline Tracing” –PipelineTracingEnabled $false –ContentConversionTracingEnabled $false


Analyzing PIPELINING
---------------------------------------

Here are the instructions:

1.            Pull up the Exchange Management Shell on one of the Hub Transport Servers first.
2.            Run the following command
Set-TransportServer –Identity “HubTransportServerName” -PipelineTracingPath  “C:\PipelineLogs”  -PipelineTracingSenderAddress  “EmailAddressOfSender” 
-PipelineTracingEnabled $true  
3.            Log on to another Hub Server and run the above cmdlet by replacing the Hub Transport name (I’m asking here to logon to another Hub server because I want to avoid the replication         
                problem)
4.            You can also specify other “Pipeline Tracing Path”. I have specified “C:\PipelineLogs” for an example here. Please go to this folder and check if Network Service permissions are 
                there.
5.            Run Get-TransportServer –Identity <HubServerName> | fl *pipe* on Exchange Management Shell and hit enter. Please check and make sure that result of this cmdlet matches with   
               what you have specified in Step # 2.
6.            Once the email has been received, you’ll see MessageSnapshot folder on one of the Hub servers which has processed the message.
7.            Zip the Message Snapshot folder and send it to me over email.
8.            Run the following cmdlet to Disable the Pipeline Tracing
Set-TransportServer –Identity <HubTransportServerName>  -PipelineTracingEnabled $false  
9.            Please run the above cmdlet 2 times by replacing the Hub server name 

PS: Enable Pipeline only on server where it requires to analyze the data



Get-TransportAgent
Get-Transportrule

Get-TransportServer


Moving the queue database
=====================================
Move-TransportDatabase.ps1 -QueueDatabasePath: D:\Exchsrvr\TransportRoles\data\Queue -QueueDatabaseLoggingPath: D:\Exchsrvr\TransportRoles\data\Queue

OR

rename the D: drive instead of C: in the EdgeTransport.exe.config
for "QueueDatabasePath"
     "QueueDatabaseLoggingPath"
     "IPFilterDatabasePath"
     "IPFilterDatabaseLoggingPath"

     "TemporaryStoragePath"

---------------------------------------------------------------------------------------------
ProtocolDefault  Secure Port
HTTP     80443RPC over HTTP
IS6001
Directory Referral 6002
DSProxy/NSPI6004
IMAP4   143993
NNTP   119563
POP3    110995
SMTP     2525
LDAP389636
LDAP5038950636
RDP3389
LINKstate 691
DC3269/3268 
FTP21
RPC135
DHCP Server 67
DNS53
Hub to Edge50389
Hub to Edge50636

--------------------------------------------------------------------------------------
Want to find Only Exchange 2013 server in the Organization 

Get-ExchangeServer | Where-object {$_.AdmindisplayVersion -like "*15*"}


Good website for the above command in Shell
http://binarynature.blogspot.com/2013/04/get-exchange-server-version-and-update-info-with-powershell.html


Get-ExchangeServer | Where-object {$_.AdmindisplayVersion -like "*15*"} | Select-object ,,,,,, | FT -autosize 


--------------------------------------------------------------------
RBAC Role Group Membership Reporting
https://gallery.technet.microsoft.com/office/RBAC-Role-Group-Membership-ed4e12ad



Get-User -ResultSize unlimited | where {$_.linkedmasteraccount -eq "NT AUTHORITY\SELF" -and $_.recipienttypedetails -ne "RoomMailbox" -and $_.recipienttypedetails -ne "Equipmentmailbox" -and $_.recipienttypedetails -ne "DiscoveryMailbox"} | select name | ft



Start Exchange Service

Get-Service *Exchange* | Start-Service