Advertisement
tedeansiii

Auto-reply rule

Jan 4th, 2017
468
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. param(
  2. [string]$username,
  3. [string]$LastDay
  4. )
  5. $Email = Read-Host "Is there a Forwarding Address? "
  6.  
  7. # Password
  8. . "F:\powershell\encPassword\Password.ps1"
  9. $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($MyCredential.Password)
  10. $uenc = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
  11.  
  12. ## Get the Mailbox to Set Auto-Reply on
  13. $MailboxName = $username
  14. #$MailboxName = Read-Host "Who are we Setting Auto-Reply on"
  15.  
  16. #Set other Variables
  17. $Account = Get-ADUser -Identity $MailboxName
  18. $FName = $Account.GivenName
  19. $LName = $Account.Surname
  20. $FullName = "$FName $LName"
  21. #$DomainLogon = "domain\user"
  22. $DomainLogon = "domain\$($MyCredential.UserName)"
  23. $RuleName = "$MailboxName Auto-Reply Rule"
  24.  
  25. try     {
  26.         Get-PSSession | Remove-PSSession
  27.         }
  28. catch   {
  29.         "No Existing Remote Exchange Sessisons to Terminate"
  30.         }
  31.  
  32. $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://<fq exchange server>/PowerShell/ -Authentication Kerberos -Credential $myCredential
  33. Import-PSSession $Session -AllowClobber
  34.  
  35. #Get Current User credentials and setup exchange session
  36. $Mailuri = Get-Mailbox -Identity $MailboxName
  37.  
  38. try     {
  39.         Get-PSSession | Remove-PSSession
  40.         }
  41. catch   {
  42.         "No Existing Remote Exchange Sessisons to Terminate"
  43.         }
  44.  
  45. #$userCredential = Get-Credential -credential "$DomainLogon"
  46. $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$($Mailuri.ServerName).<fq exchange server domain minus server name>/PowerShell/" -Authentication Kerberos -Credential $myCredential
  47. Import-PSSession $Session -AllowClobber
  48.  
  49. #Grant Impersonation rights in Exchange Management Shell
  50. Add-ADPermission -Identity $MailboxName -User $DomainLogon -extendedRight ms-Exch-EPI-May-Impersonate
  51.  
  52. #Give Yourself Full Mailbox rights on User
  53. Add-MailboxPermission -Identity $MailboxName -User '<username (you)>' -AccessRights fullaccess
  54.  
  55. ## Load Managed API dll    
  56. Add-Type -Path 'C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll'
  57.  
  58. ## Set Exchange Version    
  59. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2 #Exchange2016 #Exchange2013_SP2
  60.  
  61. ## Create Exchange Service Object    
  62. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  63.    
  64. ## Set Credentials to use two options are available Options 1 to use explicit credentials or Option 2 use the Default (logged On) credentials    
  65.    
  66. #Credentials Option 1 using UPN for the windows Account    
  67. #$psCred = Get-Credential    
  68. $psCred = $myCredential
  69. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  70. $service.Credentials = $creds
  71.    
  72. #Credentials Option 2    
  73. #service.UseDefaultCredentials = $true    
  74.    
  75. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  76.    
  77. ## Code From http://poshcode.org/624  
  78. ## Create a compilation environment  
  79. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  80. $Compiler=$Provider.CreateCompiler()  
  81. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  82. $Params.GenerateExecutable=$False  
  83. $Params.GenerateInMemory=$True  
  84. $Params.IncludeDebugInformation=$true #$False  
  85. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  86.  
  87. $TASource=@'
  88.  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
  89.    public class TrustAll : System.Net.ICertificatePolicy {
  90.      public TrustAll() {  
  91.      }
  92.      public bool CheckValidationResult(System.Net.ServicePoint sp,
  93.        System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  94.        System.Net.WebRequest req, int problem) {
  95.        return true;
  96.      }
  97.    }
  98.  }
  99. '@  
  100. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  101. $TAAssembly=$TAResults.CompiledAssembly  
  102.  
  103. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  104. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  105. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  106.  
  107. ## end code from http://poshcode.org/624  
  108.    
  109. ## Set the URL of the CAS (Client Access Server) to use two options are availabe to use Autodiscover to find the CAS URL or Hardcode the CAS to use    
  110.    
  111. #CAS URL Option 1 Autodiscover
  112. $CASADEmail = "$MailboxName@<email domain>"
  113. $service.AutodiscoverUrl($CASADEmail,{$true})    
  114. "Using CAS Server : " + $Service.url    
  115.      
  116. #CAS URL Option 2 Hardcoded    
  117.    
  118. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  119. #$service.Url = $uri      
  120.    
  121. ## Optional section for Exchange Impersonation    
  122. $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $CASADEmail)  
  123. $tmTemplateEmail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service  
  124. $tmTemplateEmail.ItemClass = "IPM.Note.Rules.ReplyTemplate.Microsoft";  
  125. $tmTemplateEmail.IsAssociated = $true;  
  126. $tmTemplateEmail.Subject = "Please Update Contact Information";  
  127. #switch here depending on type of exit, change variable autoreply based on type
  128.  
  129. #query AD manager
  130. #$InCharge
  131. #Query AD manager phone
  132. #$ICPhone
  133. #Query AD manager email
  134. #$ICEmail
  135.  
  136. #if ($type -eq "M") {  } else {  }
  137.  
  138. if ($Email -eq "Y") {
  139. $MemberEmail = Read-Host "Please type the forwarding Email"
  140. if ($MemSubType -eq "H") { $title = "Representative " } else { $title = "Senator " }
  141. $htmlBodyString = "Effective $LastDay $title$FullName is no longer at the Institution. $Title $LName's new email address is: <a href=`"mailto:$MemberEmail`?Subject=$title$FullName`">$MemberEmail</a>. To contact your new district representative, please go to <a href=`"<website>.`"><website>.</a>."
  142. } else {
  143. $htmlBodyString = "Effective $LastDay $title$FullName is no longer at the Institution. To contact your new district representative, please go to <a href=`"<website>.`"><website>.</a>."
  144. }
  145.  
  146. #Write-Host $htmlBodyString
  147. $tmTemplateEmail.Body = New-Object Microsoft.Exchange.WebServices.Data.MessageBody($htmlBodyString);
  148. $PidTagReplyTemplateId = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x65C2, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary);
  149. $tmTemplateEmail.SetExtendedProperty($PidTagReplyTemplateId, [System.Guid]::NewGuid().ToByteArray());
  150. $tmTemplateEmail.Save([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox);
  151. $nrNewInboxRule = New-Object Microsoft.Exchange.WebServices.Data.Rule;
  152. $nrNewInboxRule.DisplayName = $RuleName;
  153. $nrNewInboxRule.Conditions.SentToOrCcMe = $true;
  154. $nrNewInboxRule.Exceptions.FromAddresses.Add("<ISDgroupemail@domain>");
  155. $nrNewInboxRule.Actions.ServerReplyWithMessage = $tmTemplateEmail.Id;
  156. $nrNewInboxRule.Actions.Delete = $true;
  157. $cnCreateNewRule = New-Object Microsoft.Exchange.WebServices.Data.createRuleOperation[] 1;
  158. $cnCreateNewRule[0] = $nrNewInboxRule;
  159. $service.TraceEnabled = $True;
  160. $service.UpdateInboxRules($cnCreateNewRule,$true);
  161.  
  162.  
  163. #Revoke Full Mailbox rights on User for Yourself
  164. Remove-MailboxPermission -Identity $MailboxName -User '<username (you)>' -AccessRights fullaccess -Confirm:$False
  165.  
  166. #Verify Rule was created
  167. #   Get-InboxRule -Mailbox $MailboxName
  168. #Remove Rule
  169. <#
  170. try
  171. {
  172. Remove-InboxRule -Mailbox $MailboxName -Identity $RuleName -Confirm:$False -ErrorAction Stop
  173. }
  174. catch
  175. {
  176. Write-Host "Rule cannot be found or has already been removed"
  177. break
  178. }
  179. #>
  180.  
  181.  
  182. <#
  183. ## Most current Exchange API enumeration strings
  184. <!-- Enumeration of Exchange Server versions -->
  185. <xs:simpleType name="ExchangeVersionType">
  186. <xs:restriction base="xs:string">
  187.   <xs:enumeration value="Exchange2007" />
  188.   <xs:enumeration value="Exchange2007_SP1" />
  189.   <xs:enumeration value="Exchange2009" />
  190.   <xs:enumeration value="Exchange2010" />
  191.   <xs:enumeration value="Exchange2010_SP1" />
  192.   <xs:enumeration value="Exchange2010_SP2" />
  193.   <xs:enumeration value="Exchange2012" />
  194.   <xs:enumeration value="Exchange2013" />
  195.   <xs:enumeration value="Exchange2013_SP1" />
  196.   <xs:enumeration value="Exchange2015" />
  197.   <xs:enumeration value="Exchange2016" />
  198.   <xs:enumeration value="V2015_10_05" />
  199.   <xs:enumeration value="V2016_01_06" />
  200.   <xs:enumeration value="V2016_04_13" />
  201.   <xs:enumeration value="V2016_07_13" />
  202.   <xs:enumeration value="V2016_10_10" />
  203.   </xs:restriction>
  204. </xs:simpleType>
  205. #>
  206.  
  207. #Open Webmail of Exiting User
  208. <#
  209. #Give Yourself Full Mailbox rights on User
  210. $MailboxName = '<person leaving>'
  211. Add-MailboxPermission -Identity $MailboxName -User '<username (you)>' -AccessRights fullaccess -a
  212. sleep -s 3
  213. & C:\Users\<username on pc(you, if you use chrome)>\AppData\Local\Google\Chrome\Application\chrome.exe domainmail <website>/owa/$MailboxName@<domain>/?offline=disabled#path=/options/inboxrules
  214. #>
  215.  
  216. $MailboxName = ''
  217. Add-MailboxPermission -Identity $MailboxName -User '' -AccessRights fullaccess -AutoMapping $False
  218.  
  219. Remove-MailboxPermission -Identity $MailboxName -User '' -AccessRights fullaccess -Confirm:$False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement