Taches de gestion courante avec PS/EMS
Sommaire
- Extraire la liste des utilisateurs dans une OU spécifique
- Afficher les membres d'un groupe
- Purger les membres d'un groupe
- Ajouter un utilisateur dans les mêmes groupes qu'un autre utilisateur
- Ajouter dans un groupe les mêmes membres qu'un autre groupe
- Ajouter dans un groupe de distribution les mêmes membres qu'un autre groupe
- Obtenir la taille des différents folders d'une BAL
- Obtenir la liste des groupes de sécurité auxquels un utilisateur appartient
- Obtenir la liste des groupes de distribution auxquels un utilisateur appartient
- Supprimer les membres d'un groupe en mode Bulk via fichier CSV
- Ajouter des utilisteurs en rafale (Bulk) à un groupe via fichier CSV (Exemple 1)
- Ajouter des utilisteurs en rafale (Bulk) à un groupe via fichier CSV (exemple 2 - Include Quest exemple option)
- Afficher l'ensemble des utilisateurs qui partagent le même Manager
- Gerer les files d'attente SMTP des serveurs Exchange
- Traquer les Emails (message Tracking)
- Compléments de commandes EMS pour Exchange 2010
- EMS avec Exchange 2007 (syntaxes à valider avec les nouvelles versions d'Exchange)
NB : Les exemples sont fournies pour la plupart sous forme de modèle de scripts. Certains nécessitent EMS : EMS apportent les extensions MS Exchange à Powershell, dont tout une série de CMDLETs propres au management dx'Exchange. Cependant, certains exemples de scripts ci-dessus ne nécessitent pas EMS. Par exemple pour gérer les utilisateurs et les groupes AD, Powershell suffit (avec le module ActiveDirectory).
Retour vers sommaire Powershell... Retour vers sommaire EMS...
Extraire la liste des utilisateurs dans une OU spécifique
###################################################################################################################
#
###################################################################################################################
#
# SCRIPT PREAMBLE :
# !!!!!!!!!!!!!!!!!
#
# SCRIPT NAME : EXEMPLE--GET--All-Users-From-Bulk--OU.ps1
# VERSION : 1.0
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : Use to export user and some of their properties from targeted OU to CSV files
# The list of OUs is extract from a list file place under C:\ - The file name is C:List-of-OU.csv
#
#
#
# How to use this script :
# -----------------------
# 1 - Edit C:\List-of-OU.csv and fill or edit the file to place the list of OU
# The format of each entry in the file is the distinghished name syntax of OUs : OU=xxxxx,.....,DC=xxxx,DC=xxxxxx
# EXAMPLE : OU=My_OU,OU=Users,OU=SURESNES,DC=MyCompany,DC=FR
# TIPS : Don't put a header line at the top of the file (here it's automatically process by the qualifier -HEADER of Import-CSV cmdlet)
# 2 - Launch Powershell and move to the folder where you have place the script
# 3 - Launch .\EXEMPLE--GET--All-Users-From-Bulk--OU.ps1
# 4 - The exported files will be places in C:\ of the computer from which you execute the script
#
#
#
#
# NOTE : Most of actions are executed explicitely from the DC that is defined in variable $SourceDCname below
#
#
###################################################################################################################
#
###################################################################################################################
#
#
#
# Import-module Active Directory :
# ================================
#
import-module activedirectory
#
#
# Clear the Powershell display :
# ==============================
Clear-Host
#
#
#
# Define the variables :
# ======================
# You can modify the variables as needed if your requirement evolved in the future
# Some variables are asked interactively with READ-HOST cmdlet (Lastname, Firstname,...) - Others are
# defined as constants or are calculated from the interactive one's
#
#
# This variable is used to define the source Domain Controller where the actions will be executed
$SourceDCname = "Your-Domain-Controller.yourCompany.xxxx"
#
#
# This variable is used to define an incremental number for each CSV files to create
# NB : each CSV files will correspond to the list of users in one OU :
[int]$i=1
#
#
# This variable will be used to import each entry of the CSV file that contains the OU's list :
$csv = @()
$csv = Import-Csv -header name -Delimiter ";" -Path "C:\List-of-OU.csv"
#
#
# Extraction of the list of user in the specified OUs :
# =====================================================
#
# Remind that the list of OU (Organizational Units) to explore is provide in a CSV file that you have to customize according to your needs
# For each entry of the CSV files (that correspond to an OU), we extract the list of users in a separate CSV files
# These CSV files will be placed in C:\ of the computer :
#
#
# --- Loop through all items in the CSV ---------------
#
ForEach ($ou In $csv)
{
# We write the export file index and the corresponding OU to powershell display
# Pay attention to read your powershell display from where you run the script in order to make the association between
# the export file index and the corresponding OU
#
# Display the loop number that is used as an offset for the name of each CSV export file
write-host $i
#
# Display
write-host $ou.name
#
# Command to get the user from the specified OU (OU is specified by $ou.name variable) - this command extract User in only the first level of OU (not sub OU)
Get-ADuser -server $SourceDCname -SearchBase $ou.name -SearchScope onelevel -resultsetsize $null -Filter * -Properties SamaccountName, Displayname, enabled, description, manager, Office, Canonicalname, whencreated, LastLogonDate, logoncount, lastbadpasswordattempt, accountexpirationdate | select SamaccountName, Displayname, enabled, description, manager, Office, Canonicalname, whencreated, LastLogonDate, logoncount, lastbadpasswordattempt, accountexpirationdate | sort-object Displayname | export-csv -delimiter ";" -Encoding unicode c:\export-Users-OU-Specs-yourCompany.xxxx-$i.csv
#
# TIPS : if you need to extract the list of user in alsoi the Sub OU, replace -SearchScope onelevel by "-SearchScope Subtree" in the above command
#
# At the end of each loop of the ForEach command, we increment the i variable that will be used as index for the name of exported CSV files :
#
$i=$i+1
}
write-host ""
Write-host "End of script execution"
Write-host "================================================================================================================================"
#
#
###################################################################################################################
#
###################################################################################################################
Retour...
Afficher les membres d'un groupe
###################################################################################################################
#
###################################################################################################################
#
# SCRIPT PREAMBLE :
# !!!!!!!!!!!!!!!!!
#
# SCRIPT NAME : EXEMPLE--GET--List-Members-of-a-group.ps1
# VERSION : 1.0
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : Use to get the members of a group
#
#
# How to use this script :
# -----------------------
# 1 - Lauch EMC (Exchange Management Shell)
# 2 - Move to the folder where you have place the script
# 3 - Launch .\EXEMPLE--GET--List-Members-of-a-group.ps1
# You will be asked to provide the name of the group (ex: ce.consultants) and the Path\file destination
# The result will be displayed on the screen and export to the file defined by $ExportFile variable
#
#
#
# NOTE : Actions are executed explicitely from $DCName defined below
#
#
###################################################################################################################
#
###################################################################################################################
#
#
# Default variables :
$ExportFile = "C:\MembersList.txt"
$DCName = "Your-Domain-Controller-Name"
#
#
# Ask for the name of the group :
# ===============================
#
$GRPName = read-host -Prompt "Provide the name of the group for whitch you want to display memberships "
# Ask for the path and file name that will contain the membership list for this group :
# =====================================================================================
#
$ExportFile = read-host -Prompt "Give the path (need to exist) and file name where you will export the query result (for instance, C:\Group00-Members.txt)"
#
#
# Get the members of the groups by listing their display names :
# =============================================================
#
Get-ADGroupMember $GRPName -server $DCname | ft name
Write-host ""
Write-Host "Exporting the membership to file $ExportFile"
Get-ADGroupMember $GRPName -server $DCname | ft name | out-file $ExportFile
#
#
# END OF SCRIPT ACTIONS AREA
#
#################################################################################################################
Retour...
Purger les membres d'un groupe
###################################################################################################################
#
###################################################################################################################
#
# SCRIPT DESCRIPTION :
# !!!!!!!!!!!!!!!!!!!!
#
# SCRIPT NAME : EXEMPLE--PURGE-memberships-from-a-group.ps1
# VERSION : 1.0
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : Use to purge a group from all it's memberships
#
#
# How to use this script :
# -----------------------
# 1 - Lauch EMC (Exchange Management Shell)
# 2 - Move to the folder where you have place the script
# 3 - Launch .\EXEMPLE--PURGE-memberships-from-a-group.ps1
#
# You will be asked for the name of the group
#
#
# NOTE : Most of actions are executed explicitely from Dacosta because this server has has a central place in the Active Directory replication Topology
#
#
###################################################################################################################
#
###################################################################################################################
#
# Variable to define the Domain Controller on which actions will be executed
$SourceDomainController = "Your Domain Controller FQDN"
#
# Import-module Active Directory :
# ================================
#
Import-module activedirectory
#
#
# Ask for name of the source groupe :
# ===================================
#
$GRName = read-host -Prompt "Give the group name "
#
#
# Create an object which contains all the actual memberships of the group :
# =========================================================================
#
$SourceData = Get-ADGroupMember $GRName -server $SourceDomainController
#
#
# Remove the actual memberships of the group :
# ============================================
#
foreach ($source in $SourceData) {
remove-adprincipalgroupmembership $source.distinguishedName -memberof $GRName -Server $SourceDomainController -confirm:$false}
#
#
# Display to confirm that the destination User will be purges from all it's memberships :
# =======================================================================================
#
Write-host "Now, the group $GRName will have the following members (if succeeded, you'll see nothing) "
Get-ADGroupMember -identity $GRName -Server $SourceDomainController | ft name
#
#
# END OF SCRIPT ACTIONS AREA
#
#################################################################################################################
Retour...
Ajouter un utilisateur dans les mêmes groupes qu'un autre utilisateur
###################################################################################################################
#
###################################################################################################################
#
# SCRIPT DESCRIPTION :
# !!!!!!!!!!!!!!!!!!!!
#
# SCRIPT NAME : EXEMPLE--SET--Same-SecGroups-as-reference-user.ps1
# VERSION : 1.0
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : Use to include the Destination User in the same Security Groups as the Source User
#
#
# How to use this script :
# -----------------------
# 1 - Lauch EMC (Exchange Management Shell)
# 2 - Move to the folder where you have place the script
# 3 - Launch .\EXEMPLE--SET--Same-SecGroups-as-reference-user.ps1
#
# First, you will be asked for the source user AD Login that you will enumerate the Security Groups that he belongs to
#
# Second, you will be asked for the destination user AD Login that you want to make belonging to the same Security Groups
#
#
#
# NOTE : Most of actions are executed explicitely from $SourceDCname domain controller defined below
#
#
###################################################################################################################
#
###################################################################################################################
#
#
# This variable is used to define the souce Domain Controller where the actions will be executed
$SourceDCname = Your-Domain-Controller-FQDN
#
# Import-module Active Directory :
# ================================
#
Import-module activedirectory
#
#
# Ask for Login AD of the source User - Exemple : PGUILLOUX :
# ===========================================================
#
$UserSource = read-host -Prompt "Give the source Login AD (exemple : PGUILLOUX) "
#
#
# Ask for Login AD of the destination User - Exemple : HBARB :
# ============================================================
#
$UserDest = read-host -Prompt "Give the Destination Login AD (exemple : HTHOMAS) "
#
#
# Display the source login to confirm :
# =====================================
#
Write-host "Login source is : " $UserSource
#
#
# Display what operation will be executed :
# =========================================
#
$userDestination_DispN = (get-mailbox $userDest).displayName
Write-host $UserDest " will be included in the same security groups as " $UserSource
#
#
# Enumerate Security Group Membership of source account and add the destination account to the same groups :
# ==========================================================================================================
#
# NB : you can safely ignore Error Message that says that the user already belon to a group if it is the case
foreach ($group in Get-ADPrincipalGroupMembership $UserSource -server $SourceDCname | where {$_.groupcategory -eq "security" -and $_.mail -ne ""} | select name){
# Write-host $group.name}
Add-ADPrincipalGroupMembership -identity $UserDest -Memberof $group.name -Server $SourceDCname }
#
#
# Display to confirm that the destination User will be added to same groups as source user :
# ==========================================================================================
#
Get-ADPrincipalGroupMembership -identity $UserDest -Server $SourceDCname | where {$_.groupcategory -eq "security"}
#
#
#
# END OF SCRIPT ACTIONS AREA
#
#################################################################################################################
Retour...
Ajouter dans un groupe les mêmes membres qu'un autre groupe
###################################################################################################################
#
###################################################################################################################
#
# SCRIPT DESCRIPTION :
# !!!!!!!!!!!!!!!!!!!!
#
# SCRIPT NAME : EXEMPLE--SET--Same-Members-in-group-as-reference-group.ps1
# VERSION : 1.0
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : Use to read a source group and include it's memberships to another destination group
#
#
# How to use this script :
# -----------------------
# 1 - Lauch EMC (Exchange Management Shell)
# 2 - Move to the folder where you have place the script
# 3 - Launch .\EXEMPLE--SET--Same-Members-in-group-as-reference-group.ps1
#
# First, you will be asked for the source group name
#
# Second, you will be asked for the destination group name
#
#
#
# NOTE : Most of actions are executed explicitely from $SourceDCname domain controller defined below
#
#
###################################################################################################################
#
###################################################################################################################
#
#
#
# This variable is used to define the souce Domain Controller where the actions will be executed
$SourceDCname = Your-Domain-Controller-FQDN
#
#
# NB: this method doesn't include a temporay export to CSV file
#
# Import-module Active Directory
# ------------------------------
Import-module activedirectory
#
# Ask for name of the source groupe :
# ===================================
#
$GRSource = read-host -Prompt "Give the source group "
#
#
# Ask for name of the destination group :
# ======================================
#
$GRDest = read-host -Prompt "Give the Destination group "
#
#
# Display the source and destination groups to confirm
# ====================================================
Write-host ""
Write-host ""
Write-host "Source Group is : " $GRSource
Write-host "Destination Group is : " $GRdest
#
# Display what operation will be executed
# =======================================
Write-host ""
$SourceData = Get-ADGroupMember $GRSource -server $SourceDCname
#
#
# Enumerate Security Group Membership of source group and add them as members of the destination group
# ====================================================================================================
# NB : you can safely ignore Error Message that says that the user already belong to a group if it is the case
#
Write-warning "if errors or warnings appears, please note :"
Write-warning ""
Write-warning "1 - if the group is in the forest but outside root domain, you'll get an error - You'll have to include these members manually"
Write-warning ""
Write-warning "2 - if the group already contains the group, you can safely ignore the error"
Write-warning ""
Write-warning ""
foreach ($source in $SourceData) {
add-ADPrincipalGroupMembership $source.distinguishedName -memberof $GRDest -Server $SourceDCname}
#
# Display to confirm that the destination User will be added to same groups as source user
# ========================================================================================
#
Write-host "The group $GRSource has been received the following members : "
Write-host "------------------------------------------------------------- "
Get-ADGroupMember -identity $GRDest -Server $SourceDCname | ft name
#
#
#
# END OF SCRIPT ACTIONS AREA
#
#################################################################################################################
Retour...
Ajouter dans un groupe de distribution les mêmes membres qu'un autre groupe
###################################################################################################################
#
###################################################################################################################
#
# SCRIPT PREAMBLE :
# !!!!!!!!!!!!!!!!!
#
# SCRIPT NAME : EXEMPLE--SET--Same-DL-as-reference-user.ps1
# VERSION : 1.0
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : Use to include the Destination User in the same Mailing list as the Source User
#
#
# How to use this script :
# -----------------------
# 1 - Lauch EMC (Exchange Management Shell)
# 2 - Move to the folder where you have place the script
# 3 - Launch .\EXEMPLE--SET--Same-DL-as-reference-user.ps1
#
# First, you will be asked for the source user Ad Login that you will enumerate the Mailing lists that he belongs to
#
# Second, you will be asked for the destination user AD Login that you want to make belonging to the same Mailing lists
#
#
#
# NOTE : Most of actions are executed explicitely from the server define in variable $SourceDomainController
#
#
###################################################################################################################
#
###################################################################################################################
#
#
# Variable to define the Domain Controller on which actions will be executed
$SourceDomainController = "Your Domain Controller FQDN"
#
#
#
# Ask for Login AD of the source User - Exemple : PGUILLOUX :
# ===========================================================
#
$UserSource = read-host -Prompt "Give the source Login AD (exemple : PGUILLOUX) "
#
#
# Ask for Login AD of the destyination User - Exemple : PDURAND:
# =============================================================
#
$UserDest = read-host -Prompt "Give the Destination Login AD (exemple : PDURAND) "
#
#
# Determine the source user Distinguished Name :
# ==============================================
#
$userSource_dn = (get-mailbox $userSource).distinguishedname
#
#
# Determine and display the source user Display name :
# ====================================================
#
$userSource_DispN = (get-mailbox $userSource).displayname
Write-host "Login source of mailing lists belongings : " $userSource_DispN
#
#
# Determine and display the destination user Display name :
# =========================================================
#
$userDestination_DispN = (get-mailbox $userDest).displayName
Write-host $userDestination_DispN " will be included in the same mailing lists as " $userSource_DispN
#
#
# Enumerate Mailing Lists that the source account belongs to and add the destination account to the same mailing lits :
# =====================================================================================================================
#
# NB : you can safely ignore Error Message that says that the user already belon to a group if it is the case
foreach ($group in get-distributiongroup -resultsize unlimited){
#
if ((get-distributiongroupmember $group.identity | select -expand distinguishedname) -contains $userSource_dn){Write-Host -fore Yellow $group.name
add-DistributionGroupmember -identity $group.name -Member $UserDest -DomainController $SourceDomainController -BypassSecurityGroupManagerCheck
Get-DistributionGroupmember -identity $group.name -DomainController $SourceDomainController | where {$_.name -eq $userDestination_DispN}
#
}
}
#
#
# The following code works also well so but displays only the true DL (group that are Distribution type, not security type):
# $user = Your-User-AD-Login
# ForEach ($Group in Get-DistributionGroup -resultsize unlimited) {ForEach ($Member in Get-DistributionGroupMember -identity $Group | Where {$_.alias -eq $User}) {$Group.name}}
# Works well but display all indirect Mailing lists :
# $user = Your-User-AD-Login
# Foreach ($group in get-distributiongroup -resultsize unlimited) {if ((get-distributiongroupmember $group.identity | select -expand distinguishedname) -contains $user.alias){Write-Host -fore Yellow $group.name}}
#
#
# END OF SCRIPT ACTIONS AREA
#
#################################################################################################################
Retour...
Obtenir la taille des différents folders d'une BAL
###################################################################################################################
#
###################################################################################################################
#
# SCRIPT PREAMBLE :
# !!!!!!!!!!!!!!!!!
#
# SCRIPT NAME : EXEMPLE--GET--Mailbox_Folders_Size.ps1
# VERSION : 1.0
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : Use to get the mailbox folders user's size
#
#
# How to use this script :
# -----------------------
# 1 - Lauch EMC (Exchange Management Shell)
# 2 - Move to the folder where you have place the script
# 3 - Launch .\EXEMPLE--GET--Mailbox_Folders_Size.ps1
# You will be asked to provide the user Active Directory Login (ex: PGUILLOUX)
#
#
#
#
###################################################################################################################
#
###################################################################################################################
#
#
# Import-module Active Directory :
# ================================
#
Import-module activedirectory
#
#
# Ask for Login AD of the User - Exemple : MCHEV :
# ================================================
#
$User = read-host -Prompt "Give the Login AD or Alias (exemple : PGUILLOUX) of the user for which you want to display mailbox folders size"
#
#
# Convert $User to PS Object and obtain display name :
# ====================================================
#
$UserObj = get-aduser $User
$displayName = $UserObj.Name
#
#
# Display the login to confirm :
# ===============================
#
Write-host ""
Write-host ""
Write-host "The user's folder being check is : $DisplayName"
Write-host ""
#
#
# Get the mailbox folders user's size :
# =====================================
#
Get-MailboxfolderStatistics $User | ft name,folderpath,FolderAndSubfolderSize,ItemsInFolder,FolderSize -autosize
#
#
#
#
# END OF SCRIPT ACTIONS AREA
#
#################################################################################################################
Retour...
Obtenir la liste des groupes de sécurité auxquels un utilisateur appartient
###################################################################################################################
#
###################################################################################################################
#
# SCRIPT DESCRIPTION :
# !!!!!!!!!!!!!!!!!!!!
#
# SCRIPT NAME : EXEMPLE--GET--SecGroups-a-user-belongs-to.ps1
# VERSION : 1.O
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : Use to display all groups to which a user belongs
#
#
# How to use this script :
# -----------------------
# 1 - Lauch EMC (Exchange Management Shell)
# 2 - Move to the folder where you have place the script
# 3 - Launch .\EXEMPLE--GET--SecGroups-a-user-belongs-to.ps1
# You will be asked to provide the user Active Directory Login (ex: PGUILLOUX)
#
#
#
# NOTE : Most of actions are executed explicitely from $SourceDCname domain controller defined below
#
#
###################################################################################################################
#
###################################################################################################################
#
#
# Import-module Active Directory :
# ================================
Import-module activedirectory
#
#
# This variable is used to define the souce Domain Controller where the actions will be executed
$SourceDCname = Your-Domain-Controller-FQDN
#
# Ask for Login AD of the User - Exemple : PGUILLOUX :
# ====================================================
#
$User = read-host -Prompt "Give the Login AD (exemple : PGUILLOUX) of the user for which you want to display all Security Groups he or she belongs "
#
# Display the login to confirm :
# ===============================
"The user " + $User + " is a member of the following security groups:"
#
#
# Get only the groups of type security for that users :
# =====================================================
#
Get-ADPrincipalGroupMembership $User -server $SourceDCname | where {$_.groupcategory -eq "security"} | select name
#
#
#
#
# END OF SCRIPT ACTIONS AREA
#
#################################################################################################################
Obtenir la liste des groupes de distribution auxquels un utilisateur appartient
######################################################################################################
######################################################################################################
#
# SCRIPT PREAMBLE :
# !!!!!!!!!!!!!!!!!
#
# SCRIPT NAME : EXEMPLE--GET--DL-a-user-belongs-to.ps1
# VERSION : 1.1
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : Use to display the Distribution Groups to which a user belongs
#
#
# How to use this script :
# -----------------------
# 1 - Lauch EMC (Exchange Management Shell)
# 2 - Move to the folder where you have place the script
# 3 - Launch .\EXEMPLE--GET--DL-a-user-belongs-to.ps1
# You will be asked to provide the user Active Directory Login (ex: PGUILLOUX)
#
#
#
#
######################################################################################################
######################################################################################################
#
#
#
# You will be asked to provide the user Ad Login
#
#
# Ask for Login AD of the User - Exemple : MCHEV :
# =======================================
#
$User = read-host -Prompt "Give the Login AD or Alias of the user for which you want to display all distribution groups he or she belongs "
#
#
# Obtain the DN of the user :
# =====================
#
$user_dn = (get-mailbox $user).distinguishedname
#
#
# Display the login to confirm :
# =======================
#
"The user " + $User + " is a member of the following groups:"
#
#
# Get only the groups of type mailing lists for that users :
# ===========================================
#
foreach ($group in get-distributiongroup -resultsize unlimited){
if ((get-distributiongroupmember $group.identity | select -expand distinguishedname) -contains $user_dn){Write-Host -fore Yellow $group.name}
}
#
#
# END OF SCRIPT ACTIONS AREA
#
######################################################################################################
Retour...
Supprimer les membres d'un groupe en mode Bulk via fichier CSV
######################################################################################################
######################################################################################################
#
# SCRIPT PREAMBLE :
# !!!!!!!!!!!!!!!!!
#
# SCRIPT NAME : EXEMPLE--REMOVE--Bulk-remove-from-a-group.ps1
# VERSION : 1.0
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : Use to remove list of CSV users from a group
#
#
# How to use this script :
# -----------------------
# 1 - Prepare a CSV file with the list of the user to remove
# Exemple of content :
# --------------------
# Jean Gracien
# Hélène Rosy
# Eric Bellamy
# Sophie Calon
# 2 - Save the file as C:\UserList.csv
# 3 - Lauch EMC (Exchange Management Shell)
# 4 - Move to the folder where you have place the script
# 5 - Launch .\EXEMPLE--REMOVE--Bulk-remove-from-a-group.ps1
#
# You will be asked for the name of the group
#
#
# NOTE : Most of actions are executed explicitely from $SourceDCname domain controller defined below
#
#
######################################################################################################
######################################################################################################
#
#
# Import-module Active Directory :
# ================================
#
Import-module activedirectory
#
#
# This variable is used to define the souce Domain Controller where the actions will be executed
$SourceDCname = Your-Domain-Controller-FQDN
#
# Ask for name of the group from which list of users in the CSV file have to be removed :
# ===================================================================
#
$GRName = read-host -Prompt "Give the group name "
#
#
# Import CSV file contents
$csv = @()
$csv = Import-Csv -Delimiter "," -Path "C:\UserList.csv"
#
#
# Remove the list of users in the CSV file from the group :
# ============================================
ForEach ($user In $csv)
{$UserObj = get-ADuser $User
if ($userObj -ne $Null) {write-host -fore DarkMagenta "Removing $User from group $GRName"
remove-adprincipalgroupmembership $userObj.distinguishedName -memberof $GRName -Server $SourceDCname -confirm:$false}
}
#
#
# Display to confirm that the destination User will be purges from all it's memberships :
# ===================================================================
#
Write-host "Now, the group $GRName will keep the following members"
Get-ADGroupMember -identity $GRName -Server $SourceDCname | ft name
#
#
#
# END OF SCRIPT ACTIONS AREA
#
######################################################################################################
Retour...
Ajouter des utilisateurs en rafale (Bulk) à un groupe via fichier CSV
Exemple 1
######################################################################################################
######################################################################################################
#
# SCRIPT PREAMBLE :
# !!!!!!!!!!!!!!!!!
#
# SCRIPT NAME : EXEMPLE--ADD--Bulk-add-to-a-group.ps1
# SCRIPT VERSION : 1.0
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : Use to add lists of CSV users from a file to a group
#
#
# How to use this script :
# -----------------------
# 1 - Prepare a CSV file with the list of the user to remove
# Exemple of content :
# --------------------
# Jean-Marc Oreste
# Thierry Jovial
# André Louis
# Anette Demarche
# 2 - Save the file as C:\UserList.csv
# 3 - Lauch EMC (Exchange Management Shell)
# 4 - Move to the folder where you have place the script
# 5 - Launch .\EXEMPLE--ADD--Bulk-add-to-a-group.ps1
#
# You will be asked for the name of the group
#
##
#
#
######################################################################################################
######################################################################################################
#
# SCRIPT EXECUTION :
# !!!!!!!!!!!!!!!!!!
#
# Import-module Active Directory :
# =========================
#
Import-module activedirectory
#
# The following variable is used to define the souce Domain Controller where the actions will be executed
#
# NOTE : it is better that actions are executed explicitely from a central position Domain-Controller compared to your Active Directory Topology
# please, define your central domain controller with the variable $SourceDCname
$SourceDCname = Your-Central-Domain-Controller.your-domainFQDN
#
# Ask for name of the group from which list of users in the CSV file have to be removed :
# ====================================================================
#
$GRName = read-host -Prompt "Give the group name (exemple : GRP_Share0001)"
#
#
# Import CSV file contents
# In this example, the CSV filename is ListUsers
$csv = @()
$csv = Import-Csv -Delimiter "," -Path "C:\ListUsers.csv"
#
#
# Remove the list of users in the CSV file from the group :
# ============================================
#
ForEach ($user In $csv)
{$userObj = get-aduser -filter {displayname -like $user}
if ($userObj -ne $Null) {write-host -fore DarkMagenta "Removing $User from group $GRName"
add-adprincipalgroupmembership $userObj.distinguishedName -memberof $GRName -Server $SourceDCname -confirm:$false}
}
#
#
# Display to confirm that the destination User will be purges from all it's memberships :
# =======================================================================================
#
Write-host "Now, the group $GRName will keep the following members"
Get-ADGroupMember -identity $GRName -Server $SourceDCname | ft name
#
#
#
# END OF SCRIPT ACTIONS AREA
#
######################################################################################################
Retour...
Ajouter des utilisateurs en rafale (Bulk) à un groupe via fichier CSV
Exemple 2
######################################################################################################
######################################################################################################
#
# SCRIPT PREAMBLE :
# !!!!!!!!!!!!!!!!!
#
# SCRIPT NAME : EXEMPLE--ADD--Bulk-add-to-a-group.ps1
# SCRIPT VERSION : 1.0
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : Use to add lists of CSV users from a file to a group
#
#
# How to use this script :
# -----------------------
# 1 - Prepare a CSV file with the list of the user to remove
# The names had to be provides by SamAccountName (i.e. the Pre-windows 2000 Logon Name)
# For exemple, for Jean-Marc Oreste, the logon name is JMOreste in our exempole
# Exemple of content :
# --------------------
# JMOreste,
# TJovial,
# ALouis,
# ADemarche,
# 2 - Save the file as C:\UserList.csv
# 3 - Lauch EMC (Exchange Management Shell)
# 4 - Move to the folder where you have place the script
# 5 - Launch .\EXEMPLE--ADD--Bulk-add-to-a-group.ps1
#
# You will be asked for the name of the group
#
##
#
#
######################################################################################################
######################################################################################################
#
# SCRIPT EXECUTION :
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#
#
######################################################################################################
#
# Ask for name of the group from which list of users in the CSV file have to be removed :
# =======================================================================================
#
$GRName = read-host -Prompt "Give the group name (exemple : MY_Global-Group-Name01)"
#
#
# Display to confirm that the destination User will be purges from all it's memberships :
# =======================================================================================
#
Write-host "The group were the CSV file lists will be imported is : $GRName"
#
######################################################################################################
#
# Importing the CSV file in an object (will be used below)
# Import CSV file contents
# In this example, the CSV filename is ListUsers
# The files need to include only a list of the SamAccountName to include in the a column of the file
# Below, the parameter "-Header a" refers to the "a" column of the CSV file
$csv = @()
# $csv = Import-Csv -Delimiter "," -Path "C:\Scripts\listusers.csv"
$csv = Import-Csv -Header a -Path "C:\Scripts\listusers.csv"
#
######################################################################################################
#
# If not using Quest CmdLets
#
# Import-module Active Directory :
# ================================
#
Import-module activedirectory
#
#
# Defining the default DC:
# ========================
#
# The following variable is used to define the souce Domain Controller where the actions will be executed
#
# NOTE : it is better that actions are executed explicitely from a central position Domain-Controller compared to your Active Directory Topology
# please, define your central domain controller with the variable $SourceDCname
$SourceDCname = "MyDCName"
#
# Add the list of users in the CSV file to the group :
# ====================================================
#
ForEach ($user In $csv)
{
$userObj = get-aduser $user.a
write-host $userObj
if ($userObj -ne $Null) {write-host -fore DarkMagenta "Adding $User to group $GRName"
add-adprincipalgroupmembership $userObj.distinguishedName -memberof $GRName -Server $SourceDCname -confirm:$false}
}
#
#
######################################################################################################
#
# If using Quest CmdLets
#
# AVERTISSEMENT : The default search was configured to retrieve only the first 1000 results. To retrieve more results, increase
# the size limit using the -SizeLimit parameter or set the default size limit using Set-QADPSSnapinSettings with the
# -DefaultSizeLimit parameter. Use 0 as the value of size limit to retrieve all possible search results.
Set-QADPSSnapinSettings -DefaultSizeLimit 0
#
# Add the list of users in the CSV file to the group :
# ====================================================
#
ForEach ($user In $csv)
{$userObj = get-qaduser -SamAccountName $user.a
write-host "valeur1 : $user"
write-host "valeur2 : $userObj"
if ($userObj -ne $Null) {write-host -fore DarkMagenta "Adding $User to group $GRName"
add-QadMemberOF $userObj -group $GRName -confirm:$false -verbose}
}
#
######################################################################################################
#
Write-host "End of operation"
#
#
#
# END OF SCRIPT ACTIONS AREA
#
######################################################################################################
######################################################################################################
Retour...
Afficher l'ensemble des utilisateurs qui partagent le même Manager
######################################################################################################
#######################################################################################################
#
# SCRIPT PREAMBLE :
# !!!!!!!!!!!!!!!!!
#
# SCRIPT NAME : EXEMPLE--Display-all-accounts-with-the-same-Manager.ps1
# VERSION : 1.0
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : Retrieve all account manage by the same Manager
#
#
# How to use this script :
# -----------------------
# 1 - Lauch EMC (Exchange Management Shell)
# 2 - Move to the folder where you have place the script
# 3 - Launch .\EXEMPLE--Display-all-accounts-with-the-same-Manager.ps1
#
# First, you will be asked for the source user AD Login that you will enumerate the Security Groups that he belongs to
#
# Second, you will be asked for the destination user AD Login that you want to make belonging to the same Security Groups
#
#
#
#
#
######################################################################################################
######################################################################################################
#
#
#
# Import-module Active Directory :
# ================================
#
Import-module activedirectory
#
#
# Ask for Login AD of login of the manager - Exemple : PGUILLOUX :
# ===================================================
#
Write-host "You will be ask to provide the login for a user that is defined as manager for other people"
Write-host "then, all user accounts for which this user is define to be the manager will be dispayed"
write-host ""
$ManagerName = read-host -Prompt "Give the name of the manager to check (exemple : PGUILLOUX)"
Write-host "beginning search..."
Write-host ""
$ManagerNameObj = Get-ADUser $ManagerName
Get-ADUser -Filter {manager -eq $ManagerNameObj.DistinguishedName}
#
#
# END OF SCRIPT ACTIONS AREA
#
######################################################################################################
Retour...
Gerer les files d'attente SMTP des serveurs Exchange
######################################################################################################
######################################################################################################
#
# PREAMBLE :
# !!!!!!!!!!
#
#
# REDACTOR OF SCRIPT : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : manage mail queues on Microsoft Exchange
#
#
######################################################################################################
######################################################################################################
#
# Voir toutes les files d'attente du serveur :
# ----------------------------------------------------
#
[PS] C:\WINDOWS\system32>get-queue | ft -AutoSize
Identity DeliveryType Status MessageCount NextHopDomain
-------- ------------ ------ ------------ -------------
...................
#
# Voir les files d'attente suspendue du serveur :
# ----------------------------------------------------------
#
[PS] C:\WINDOWS\system32>get-queue -Filter {status -eq "suspended"}
Identity DeliveryType Status MessageCount NextHopDomain
-------- ------------ ------ ------------ -------------
...................
#
# Voir les files d'attente en 'Retry" du serveur :
# --------------------------------------------------------
#
[PS] C:\WINDOWS\system32>get-queue -Filter {status -eq "retry"}
Identity DeliveryType Status MessageCount NextHopDomain
-------- ------------ ------ ------------ -------------
...................
#
# Rechercher un ou plusieurs mail dans les files d'attente du serveur via des critères de noms d'expéditeur :
# --------------------------------------------------------------------------------------------------------------------------------------
#
[PS] C:\WINDOWS\system32>Get-Message -Filter {Fromaddress -like "*@yourcompany.tld"}
Identity DeliveryType Status MessageCount NextHopDomain
-------- ------------ ------ ------------ -------------
...................
[PS] C:\WINDOWS\system32>Get-Message -Filter {Fromaddress -like "*@othercompany.com"} | ft -AutoSize
Identity DeliveryType Status MessageCount NextHopDomain
-------- ------------ ------ ------------ -------------
...................
######################################################################################################
Retour...
Traquer des messages (messages tracking)
######################################################################################################
######################################################################################################
#
#
# REDACTOR : Patrice GUILLOUX - EMAIL : PGUILLOUX@OUTLOOK.COM
#
#
# GOAL : commandes powershell (Exchange Management Shell) pour retrouver le cheminement de messages
#
#
######################################################################################################
#
# Retrouver un ou plusieurs messages dont l'expéditeur est Exemple@exemple-external-company.com récu par le serveur et sur un intervalle de temps précis :
get-messagetrackinglog -Sender "Exemple@exemple-external-company.com" -EventID "RECEIVE" -Start "02/02/2015 11:33:00" -End "17/02/2015 11:43:00"
#
#
#
# Retrouver un ou plusieurs messages dont l'expéditeur est Email-Adress-to-check et reçu par le serveur dans l'intervalle de temps spécifié :
# -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
[PS] C:\WINDOWS\system32>get-messagetrackinglog -Sender "Email-Adress-to-check" -Server "Your-Exchange-mailbox-Server" -EventID "RECEIVE" -Start "01/01/2015 09:15:00" -End "01/01/2015 09:25:00"
#
#
# Idem avec une présentation Format Table :
# ------------------------------------------------------
[PS] C:\WINDOWS\system32>get-messagetrackinglog -Sender "Email-Adress-to-check" -Server "Your-Exchange-mailbox-Server" -EventID "RECEIVE" | ft -AutoSize
EventId Source Sender Recipients MessageSubject
------- ------ ------ ---------- --------------
.....................
#
# Retrouver un ou plusieurs messages dont l'expéditeur est Email-Adress-to-check et envoyé par le serveur dans l'intervalle de temps spécifié :
# -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
[PS] C:\WINDOWS\system32>get-messagetrackinglog -Recipients:Email-Adress-to-check -Server "Your-Exchange-mailbox-Server" -EventID "RECEIVE" -Start "01/01/2015 09:15:00" -End "01/01/2015 09:25:00"
#
#
# Idem avec une présentation Format Table :
# ------------------------------------------------------
[PS] C:\WINDOWS\system32>get-messagetrackinglog -Recipients:Email-Adress-to-check -Server "Your-Exchange-mailbox-Server" -EventID "RECEIVE" | ft -AutoSize
EventId Source Sender Recipients MessageSubject
------- ------ ------ ---------- --------------
.....................
[PS] C:\WINDOWS\system32>$msgs = Get-TransportServer | Get-MessageTrackingLog -Recipients "EmailAdresse" -resultsize unlimited
[PS] C:\WINDOWS\system32>$msgs.count
18136
[PS] C:\WINDOWS\system32>$msgs | Group-Object -Property Sender | Select-Object name,count | sort count -desc | select -first 10 | ft -auto
Name Count
---- -----
......................
TIPs : Où trouver les messages --> Default message tracking folder : \\Your-Exchange-mailbox-Server\c$\Program Files\Microsoft\Exchange Server\V14\TransportRoles\Logs\MessageTracking
#
##
#
# Exemples de commandes pour retrouver des mails par rapport à des dates, le statut (Receive, failed,...) :
# ---------------------------------------------------------------------------------------------------------------------------------
#
[PS] C:\WINDOWS\system32>get-messagetrackinglog -Recipients:External-user-to-trace@exemple-external-company.com -Sender "Internal-User-to-trace@your-company.com" -EventID "SEND" -Start "02/02/2015 11:47:00" -End "02/17/2015 11:57:00"
[PS] C:\WINDOWS\system32>get-messagetrackinglog -Sender "External-user-to-trace@exemple-external-company.com" -EventID "RECEIVE" -Start "02/02/2015 11:47:00" -End "02/17/2015 11:57:00"
[PS] C:\WINDOWS\system32>get-messagetrackinglog -Sender "External-user-to-trace@exemple-external-company.com" -EventID "RECEIVE" -Start "02/02/2015 11:47:00" -End "02/17/2015 11:57:00" -MessageSubject "RE: Harel sample"
[PS] C:\WINDOWS\system32>get-messagetrackinglog -Sender "External-user-to-trace@exemple-external-company.com" -EventID "RECEIVE" -Start "02/02/2015 11:47:00" -End "02/17/2015 11:57:00" -MessageSubject "RE: Harel sample" | fl
[PS] C:\WINDOWS\system32>get-messagetrackinglog -Sender "External-user-to-trace@exemple-external-company.com" -Server "Your-Internal-Exchange-Server" -EventID "FAIL" -Start "02/02/2015 13:01:00" -End "02/17/2015 13:11:00" | ft -autosize
[PS] C:\WINDOWS\system32>get-messagetrackinglog -Sender "External-user-to-trace@exemple-external-company.com" -Server "Your-Internal-Exchange-Server" -EventID "FAIL" -Start "02/02/2015 13:01:00" -End "02/17/2015 13:11:00" | fl
[PS] C:\WINDOWS\system32>get-messagetrackinglog -Sender "External-user-to-trace@exemple-external-company.com" -Server "Your-Internal-Exchange-Server" -EventID "FAIL" -Start "02/02/2015 13:01:00" -End "02/17/2015 13:11:00" | ft timestamp,eventid,messagesubject,sender,recipients,recipientStatus,TotalBytes,ReturnPath,clientHostname,messageid -autosize
[PS] C:\WINDOWS\system32>get-messagetrackinglog -Sender "Internal-User-to-trace@your-company.com" -Server "Your-Internal-Exchange-Server" -EventID "FAIL" -Start "02/02/2015 13:01:00" -End "02/17/2015 13:11:00" | ft timestamp,eventid,messagesubject,sender,recipients,recipientStatus,TotalBytes,ReturnPath,clientHostname,messageid -autosize
#
#
#
#
######################################################################################################
Retour...
Compléments de commandes EMS pour Exchange 2010
######################################################################################################
######################################################################################################
#
# certaines commandes sont remplacer par rapport à Exchange 2007. Par exemple Move-Mailbox et ses dérivés sont remplacés par
New-#moverequest
#
# Quelques nouvelles commandes :
#
# Pour avoir les modues Active Directory et surtout Exchange 2010 chargés dans votre session Powershell :
Import-module activedirectory
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
#
#
#Activer la licence de votre Exchange :
Set-ExchangeServer –Identity 'nomdevotreserveurServerName’ –ProductKey 'votrecle'
#
# Créer une boîte aux lettres :
New-Mailbox -Name 'nomaffiché' -Alias 'alias' -OrganizationalUnit 'MYOU' -UserPrincipalName 'login' -SamAccountName 'ancienlogin' -FirstName '' -Initials '' -LastName '' -Database 'votreserveur\nomdevotrebanquee' [-Room <$false|$true> | -Equipment <$false|$true>
#
# Activer l'archivage d'une boîte :
Enable-Mailbox mondomaine.local/MYOU/MDeniel –Archive
#
# Désactiver l’archivage d’une boîte aux lettres :
Disable-Mailbox mondomaine.local/MYOU/MDeniel –Archive*
#
# Désactiver un groupe de distribution :
Disable-DistributionGroup -Identity 'mondomaine.local/MYOU/Ventes'
#
# Visualiser les membres d’un groupe de distribution :
Get-DistributionGroupMember -Identity 'mondomaine.local/MYOU/Ventes'
#
#
#
Récupérer des infos des comptes AD pour les Bals partagés :
#
$mylist = get-mailbox -RecipientTypeDetails sharedmailbox
#
foreach ($i in $mylist) {get-aduser $i.samaccountname -properties * | select name,enabled,PasswordExpired,Passwordlastset,PasswordNeverExpires | Export-Csv ("c:\Exports\Liste-des-BALs-SHARED.csv") -delimiter ";" -append -NoTypeInformation -Encoding UTF8}
#
Attention, pour que -Append fonctionne (Export-CSV), il faut au minimum Powershell v3.0 !!!
#
Retrouver le cheminement des Emails (Emails Tracking) :
#
Attention de bien fournir le e paramètre avec le nom du serveur sinon ne fonctionne pas !!!
#
get-messagetrackinglog -Sender "adresse@example.com" -Server "Your-server-Exchange" -EventID "RECEIVE" | select @{Name='Destinataires';Expression={[string]::join(", ", ($_.recipients))}} ,messagesubject,timestamp | Export-csv ("c:\exports\Mail-Send-Example.csv") -delimiter ";" -NoTypeInformation -Encoding UTF8
#
Récuperer les infos des groupes de distribution dynamique :
Get-DynamicDistributionGroup Nom-du-Groupe | fl name,Recipientcontainer
Get-DynamicDistributionGroup Nom-du-Groupe | fl name,AcceptMessagesOnlyFrom
Get-DynamicDistributionGroupNom-du-Groupe| fl name,AcceptMessagesOnlyFromSendersOrMembers
Get-DynamicDistributionGroup | ft Name,DisplayName,RecipientContainer,Addresslistmembership,RecipientFilter,LdapRecipientFilter,AcceptMessagesOnlyFrom,AcceptMessagesOnlyFromSendersOrMembers -auto -wrap
Pour palier l'export-CSV pour les champs multivalués (ici AddressListMemberShip, AcceptMessagesOnlyFrom,AcceptMessagesOnlyFromSendersOrMembers sont multivalués) :
Utilisez ces commandes au préalable afin de vérifier la syntaxe avant de tester avec Export-CSV :
Get-DynamicDistributionGroup | ft Name,@{Name=’Addresslistmembership';Expression={[string]::join(“;”, ($_.Addresslistmembership))}}
Get-DynamicDistributionGroup | ft Name,@{Name=’AcceptMessagesOnlyFromSendersOrMembers';Expression={[string]::join(“;”, ($_.AcceptMessagesOnlyFromSendersOrMembers))}}
Get-DynamicDistributionGroup | ft Name,@{Name=’AcceptMessagesOnlyFrom';Expression={[string]::join(“;”, ($_.AcceptMessagesOnlyFrom))}}
#
Export dans un CSV des membres d'un groupe de distribution dynamique :
Get-DynamicDistributionGroup Your-Groupe-Distribution | select Name,@{Name='Addresslistmembership';Expression={[string]::join(", ", ($_.Addresslistmembership))}} | Export-Csv c:\export-Your-Group-Name-with-multivalue-properties.csv -delimiter ";" -NoTypeInformation -Encoding UTF8
#
#
Pour obtenir la liste complète des utilisateurs de chaque groupe Dynamique Exchange :
$Mydistbdyn = Get-DynamicDistributionGroup Your-Example-Groupe-Distribution
Vérification des commandes avant export-CSV :
get-recipient -RecipientPreviewFilter $Mydistbdyn.ldapRecipientfilter -ResultSize Unlimited | Ft name,displayname,primarySmtpAddress -autosize
ou
get-recipient -RecipientPreviewFilter $Mydistbdyn.Recipientfilter -ResultSize Unlimited | Ft name,displayname,primarySmtpAddress -autosize
Export dans un fichier CSV (utilisez Select-objet) :
get-recipient -RecipientPreviewFilter $Mydistbdyn.ldapRecipientfilter -ResultSize Unlimited | select-object name,displayname,primarySmtpAddress | Export-Csv c:\Member-Your-Group-ldap.csv -delimiter ";" -NoTypeInformation -Encoding UTF8
ou
get-recipient -RecipientPreviewFilter $Mydistbdyn.Recipientfilter -ResultSize Unlimited | select-object name,displayname,primarySmtpAddress | Export-Csv c:\Member-Your-Group.csv -delimiter ";" -NoTypeInformation -Encoding UTF8
Pour limiter sur une partie d’où (si RecipientContainer est définit sur une partie de l'annuaire ou niveau du Dynamique Distribution Group) :
(remplacer par vos valeurs)
get-recipient -RecipientPreviewFilter $Mydistbdyn.Recipientfilter -OrganizationalUnit 'YourDomainFQDN/OUxxx/OUyyyyy' -ResultSize Unlimited | select-object name,displayname,primarySmtpAddress | Export-Csv c:\Member-Your-Group.csv -delimiter ";" -NoTypeInformation -Encoding UTF8
Pour le faire en une seule ligne de commande :
Get-Recipient -Filter (Get-DynamicDistributionGroup "Your-Group-Name").RecipientFilter -OrganizationalUnit(Get-DynamicDistributionGroup Your-Group-Name).RecipientContainer -ResultSize Unlimited
idem avec export :
Get-Recipient -Filter (Get-DynamicDistributionGroup "Your-Group-Name").RecipientFilter -OrganizationalUnit(Get-DynamicDistributionGroup Your-Group-Name).RecipientContainer -ResultSize Unlimited | select-object name,displayname,primarySmtpAddress | Export-Csv c:\Member-Your-Group-Name.csv -delimiter ";" -NoTypeInformation -Encoding UTF8
#
#
######################################################################################################
Retour...
EMS avec Exchange 2007
######################################################################################################
######################################################################################################
Enregistrer ce qu'on tape au clavier dans une session EMS :
Vous voulez enregistrer précisément ce qu'il se passe lorsque vous utilisez Exchange Management Shell.
Utilisez la cmdlet Start-Transcript : tout ce que vous faites après avoir exécuté cette cmdlet est consigné dans le fichier texte que vous spécifiez. Pour arrêter l'enregistrement de votre session, utilisez la cmdlet Stop-Transcript.
Notez que la cmdlet Start-Transcript remplace le fichier texte de destination par un fichier par défaut. Pour ajouter votre session à un fichier existant, utilisez le paramètre Append :
Start-Transcript c:\MySession.txt -Append
Afficher les services actifs du serveur :
Get-Service | where {$_.Status -eq "Running"}
Test du bon fonctionnement d'Exchange 2007 :
The first example shows how to send a test message from the server Mailbox1 to the server Mailbox2.
Test-Mailflow Mailbox1 -TargetMailboxServer Mailbox2
The second example shows how to send a test message from the server Mailbox1 to the e-mail address john@contoso.com.
In this example, the test message is being sent to a Mailbox server in a remote forest.
Test-Mailflow Mailbox1 -TargetEmailAddress john@contoso.com
Use the Get-SystemMessage cmdlet in Microsoft Exchange Server 2007 to view the delivery status notification (DSN)
Use Test-SystemHealth cmdlet to gather data about your Microsoft Exchange system and to analyze the data according to best practices
Use the Test-ServiceHealth cmdlet to test whether all the required services that are configured to start automatically on
a server have started
Boîtes aux lettres : Get-Mailbox <Mailbox Name> | Test-MapiConnectivity
Serveurs : Get-MailboxServer <Server Name> | Test-MapiConnectivity
Récupérer les journaux d'installation d'Exchange 2007 :
Get-SetupLog c:\exchangesetuplogs\exchangesetup.log
ou
Get-SetupLog c:\exchangesetuplogs\exchangesetup.log -tree
ou
Get-SetupLog c:\exchangesetuplogs\exchangesetup.log -error
ou
Get-SetupLog c:\exchangesetuplogs\exchangesetup.log - error -tree
Afficher les principaux paramètres d'Exchange 2007 :
Pour obtenir un résumé de la configuration du serveur Exchange 2007:
Get-ExchangeServer
Get-ExchangeServer -Status | Format-List
Pour obtenir des informations supplémentaires, voici une liste de quelques commandes intéressantes :
Get-MailboxDatabase -Server <Server Name> -Status | Format-List
Get-OrganizationConfig
Get-ExchangeAdministrator
Get-StorageGroup -Identity "Storage Group Server\First Storage Group" | Format-List
Get-MailboxDatabase -IncludePreExchange2007
Get-MailboxDatabase -Identity Server01\StorageGroup01\MailboxDatabase01 -Status | format-list
Get-MailboxDatabase -Status | format-table Name,StorageGroup,Mounted
Get-PublicFolderDatabase -IncludePreExchange2007 | Format-List
Get-MailboxFolderStatistics -Identity contoso\chris
Get-LogonStatistics -Server srvmail
Get-MailboxStatistics -Database "Your-Mailbox-BDD01"
Get-MailboxPermission -Identity Test1 | Format-List
Get-OutlookProvider -Identity EXCH | Format-List
Get-AutoDiscoverVirtualDirectory -Identity "CAS01\autodiscover(autodiscover.contoso.com)"
Afficher les paramètres des dossiers publics :
Get-PublicFolder :
Get-PublicFolder -Identity \NON_IPM_SUBTREE -Recurse | Format-List Name
Get-PublicFolder -Identity <long-term entry identifier of a public folder>
Get-PublicFolder -Identity "\Legal\Documents\Pending Litigation"
Get-PublicFolder -Identity "\Legal\Documents\Pending Litigation" -Recurse
Get-PublicFolder -Identity "\Legal\Documents\Pending Litigation" -Recurse -ResultSize Unlimited
Get-PublicFolderStatistics -Server "My Server" | Format-List
Update-PublicFolder "\Legal\Cases\My Public Folder" -Server "My Server"
Get-PublicFolder "\Legal\Cases\My Public Folder" | Update-PublicFolder -Server "My Server"
Afficher la liste des domaines pris en charge par l’organisation Exchange :
Get-AcceptedDomain |fl
Ajouter des domaines SMTP acceptés au sein de l'organisation Exchange :
New-AcceptedDomain –Namenomdudomaine –DomainName nomdudomaine –DomainType Authoritative
Ajouter en mode Bulk-insertion :
Get-Content c:\scripts\domains.txt | Foreach-Object {New-AcceptedDomain -Name $_ -DomainName $_ -DomainType Authoritative}
Lecture d’un fichier dont on spécifie le chemin avec le paramètre Path :
Ainsi la commande Get-Content –path f:\scripts\domaines.txt ouvre le fichier texte et renvoie ligne par ligne le contenu de ce fichier
De même:
Get-Content f:\scripts\domaines.txt | New-AcceptedDomain –Name $_ –DomainName $_ –DomainType Authoritative
Vérifier les files d'attente SMTP :
get-queue –SortOrder:-MessageCount –Results:1 | fl
get-message –Filter:{Queue –eq ‘Submission’ –and Status –eq ‘Retry’}
get-message –Queue <QueueIdentity> -Results:10
get-message –Filter:{Queue –eq ‘<QueueIdentity>’ –and Status –eq ‘Active’}
get-message –Filter:{Queue –eq ‘Submission’ –and Status –eq ‘Retry’}
get-message –Queue:Poison | export-message –Path: “C:\temp”
Par exemple:
Get-message -IncludeRecipientInfo -Server srvmail -ResultSize 500 -SortOrder +FromAddress,+Size|fo
rmat-list -property Fromaddress,scl,subject,Recipients
Configurer un connecteur d'envoi SMTP :
Afficher la configuration d'un connecteur d'envoi SMTP :
get-sendconnector | fl
Création d'un connecteur d'envoi :
NB : Il n'existe pas de connecteur d'envoi par défaut. Pour le créer:
New-SendConnector -Name "Connecteur Send SMTO to Internet" -Usage Internet -AddressSpaces "*" -SourceTransportServers "HubA" -DNSRoutingEnabled:$true -UseExternalDNSServersEnabled:$true
Afficher les permissions du connecteur d'envoi SMTP :
Get-AdPermission -Identity "Default SRVMAIL" | format-table -view User
Get-AdPermission -Identity "Default SRVMAIL" | format-table -view Identity
Get-AdPermission -Identity "Client SRVMAIL" | format-table -view User
Get-AdPermission -Identity "Client SRVMAIL" | format-table -view Identity
get-adpermission <id of the Receive Connector> | ft User,ExtendedRights
Exemple:
If you run
Get-AdPermission -Identity "Default ServerName" | format-table -view User
or
Get-AdPermission -Identity "Default ServerName" | format-table -view Identity
where "Default servername" is the name of the receive connector, you will see that the Anonymous logon doesn't have enought permissions, specially ms-Exch-SMTP-Accept-Any-Recipient. Then, you must run the following command:
Add-AdPermission -Identity "Default Hub1" -User "NT AUTHORITY\ANONYMOUS LOGON"
-ExtendedRights ms-Exch-SMTP-Submit,ms-Exch-SMTP-Accept-Any-Recipient,ms-Exch-Bypass-Anti-Spam where Default Hub1 is the name of your Receive Connector with Relay problems
Résultat de :
get-adpermission <id of the Receive Connector> | ft User,ExtendedRights:
User ExtendedRights
---- --------------
NT AUTHORITY\Authenticated Users {ms-Exch-SMTP-Submit}
NT AUTHORITY\Authenticated Users {ms-Exch-SMTP-Accept-Any-Recipient}
NT AUTHORITY\Authenticated Users {ms-Exch-Bypass-Anti-Spam}
MYHUB\Exchange Servers {ms-Exch-SMTP-Accept-Exch50
MYHUB\Exchange Servers {ms-Exch-Accept-Headers-Routing}
MYHUB\Exchange Servers {ms-Exch-Accept-Headers-Forest}
Modification des permissions sur le connecteur d'envoi SMTP:
Grant the ‘ms-Exch-SMTP-Accept-Authoritative-Domain-Sender’ permission to ‘Anonymous’.for the connector ‘Default EDGEB42’:
add-adpermission 'Default EDGEB42' -User 'NT AUTHORITY\ANONYMOUS LOGON' -ExtendedRights ms-Exch-SMTP-Accept-Authoritative-Domain-Sender
Another often requested example is to allow anonymous sessions to submit messages through SMTP to a Hub server. The command would be:
add-adpermission 'Default EDGEB42' -User 'NT AUTHORITY\ANONYMOUS LOGON' -ExtendedRights ms-Exch-SMTP-Submit,ms-Exch-SMTP-Accept-Any-Recipient,ms-Exch-Bypass-Anti-Spam
Configurer un Receive Connector SMTP :
Afficher la configuration d'un connecteur de réception SMTP:
get-receiveconnector | fl
Créer un nouveau connecteur de réception :
New-receiveconnector -Name 'Receive from Internet'-Type FromInternet -Bindings 0.0.0.0:25 -RemoteIPRanges 0.0.0.0- 255.255.255.255
Bonne pratique:
If the Exchange Server 2007 SMTP Server is configured as the Edge Transport Server role (the SMTP server that is directly connected to the Internet), you would typically configure 2 Receive Connectors: 1 to receive messages from the Internet (to be delivered to your organization), and one to receive messages from your organization (to be delivered to the Internet). The only information you would really need is the IP address range for the SMTP servers in your organization. (That's it.) Suppose all the SMTP servers in your own organization would all be in the following subnet: 192.168.0.0(255.255.0.0). In that case, both receive connectors can be created with the following 2 commands:
· new-receiveconnector -Name 'Receive from Internet'-Type FromInternet -Bindings 0.0.0.0:25 -RemoteIPRanges 0.0.0.0- 255.255.255.255
· new-receiveconnector -Name 'Receive from Organization'-Type FromEnterprise -Bindings 0.0.0.0:25 -RemoteIPRanges 192.168.0.0(255.255.0.0) -RelayControl Open
If a connection comes in on that server on 0.0.0.0:25, the SMTP server checks the remote IP address. If it is in 192.168.0.0(255.255.0.0), the connection gets served by the 2nd receive connector; the one with Name 'Receive from Organization'. The additional property 'RelayControl' is set to Open, which allows any computer in the network 192.168.0.0(255.255.0.0) to relay through the SMTP server. All other connections get served by the first Receive Connector, which doesn't allow relay. That Receive connector will only accept email messages to the Authoritative (or local) domains and Non-Authoritative (or remote) domains. In Beta 1, those domains have to be specified in the following file:
C:\Program Files\Microsoft\Exchange Server\TransportRoles\Shared\domains.config
If the Exchange Server 2007 SMTP Server is configured as the BridgeHead role (the SMTP server handles email traffic within your organization), a single Receive Connector gets created during setup. That Receive Connector should have all the settings such that email within a single Exchange Server 2007 only domain should flow securely.
Modifier un Receive Connector SMTP :
Pour modifier le connecteur d'envoi par défaut sur le serveur de transport HUB et qu'il puisse être utilisé pour l'expédition de message vers Internet, il faut ajouter le permissions par défaut du groupe Anonyme au connecteur tel que ci-dessous:
Set-ReceiveConnector -Name "Default Server Name" -Server Your-Exchange-Server -PermissionGroups AnonymousUsers,ExchangeUsers,ExchangeServers,ExchangeLegacyServers
Modifier la taille maximum des messages que le connecteur peut recevoir :
Set-receiveconnector 'Receive from Internet' -MaxMessageSize 25Mb
Configuration de la Pickup Directory SMTPPickup Directory :
Set-TransportServer
pour toutes les tâches de configuration du répertoire de collecte. Cette cmdlet permet d'effectuer
les changements de configuration du répertoire de collecte suivants :
- Activation ou désactivation du répertoire de collecte ;
- Spécification de l'emplacement du répertoire de collecte :Set-TransportServer Your-Exchange-Server -PickupDirectoryPath “D:\Exchange\Pickup”
- Spécification de l'emplacement du répertoire de Replay : Set-TransportServer Your-Exchange-Server -ReplayDirectoryPath “D:\Exchange\Replay”
- Spécification d'une taille maximale d'en-tête de fichier de message accepté par le répertoire de collecte ;
- Spécification d'un nombre maximal de destinataires dans un fichier de message accepté par le répertoire de collecte ;
- Spécification d'une vitesse maximale pour le traitement des fichiers de messages en messages par minute.
Ne pas confonfre avec les Bases de données SMTP - Pour déplacer la base de données SMTP et son log, modifier directement le fichier C:\Program Files\Microsoft\Exchange Server\Bin\EdgeTransport.exe.config via Notepad:
· <add key="QueueDatabasePath" value="D:\Exchange\Queue" />
· <add key="QueueDatabaseLoggingPath" value = "D:\Exchange\Queue" />
Contrôler les paramètres d'envoi vers un domaine spécifique
Vous voulez contrôler les propriétés de messages électroniques envoyés à un domaine spécifique.
Utilisez les cmdlets RemoteDomain. Créez un domaine distant à l'aide de la cmdlet New-RemoteDomain.
Tapez :
New-RemoteDomain -Name "Contoso.com Configuration" -DomainName contoso.com
Modifiez ensuite les propriétés de votre choix pour ce domaine distant à l'aide de la cmdlet Set-RemoteDomain :
Set-RemoteDomain "Contoso.com Configuration" -AutoReplyEnabled $True -AutoForwardEnabled $True
Supprimer des messages provenant d'un domaine sans générer de NDR :
Vous voulez supprimer tous les messages électroniques provenant d'un nom de domaine spécifique des files d'attente d'un serveur sans générer de rapport de non-remise (NDR).
Tapez :
Remove-Message -WithNDR $False -Filter { FromAddress -Like "*@contoso.com" }
Configuration avancée d'un serveur de transport HUBUtiliser Set-TransportServer :
Modification de la taille maximale des messages en entrée et en sortie au niveau de l'organisation· Pour connaitre les limites actuelles :
Get-TransportConfig | fl max*
Pour modifier ces limites, voici un exemple:
Set-TransportConfig -MaxReceiveSize 12MB -MaxSendSize 12MB -MaxRecipientEnvelopeLimit 5000
Sauvegarder le fichier et relancer le service Transport Microsoft Exchange
Gestion de l'Antispam integer à Exchange 2007 :
Obtenir la configuration des agents AntiSpam
Get-TransportAgent
Get-TransportAgent -Identity "Edge Rule Agent" | Format-List
Afficher les statistiques sur l'Antispam:[PS] C:\Program Files\Microsoft\Exchange Server\Scripts>.\get-AntispamTopRecipients.ps1
Name Value
---- -----
user01.test@YourDomain.example 205
user02.test@YourDomain.example 199
user03.test@YourDomain.example 186
user04.test @YourDomain.example 186
user05.test @YourDomain.example 182
christine.beaudouin@YourDomain.example 181
[PS] C:\Program Files\Microsoft\Exchange Server\Scripts>.\get-AntispamTopRBLProviders.ps1
[PS] C:\Program Files\Microsoft\Exchange Server\Scripts>.\get-AntispamTopBlockedSenders.ps1 top
[PS] C:\Program Files\Microsoft\Exchange Server\Scripts>.\get-AntispamSCLHistogram.ps1
Configurer le services POP3 :
Set-service msExchangePOP3 -startuptype automatic
Start-service -service msExchangePOP3
Autorisation de la BAL:
- Sur toutes les Bals
- Sur une Bal
Pour vérifier:
Get-PopSettings -Server SRVMAIL
Configuration du service IMAP :
Set-Service MSExchangeIMAP4 -StartupType automatic
Start-Service MSExchangeIMAP4
Get-Mailbox | Set-CASMailbox -ImapEnabled:$true
Set-ImapSettings -Sever <nom-serveur-cas> -LoginType SecureLogin -X509CertificateName <nom-certificat>
Stop-Service MSExchangeIMAP4
Start-Service MSExchangeIMAP4
Gérer les bases de données Exchange :
Afficher les statistiques sur une bases de données :
Get-MailboxStatistics -database "Your-Mailbox-BDD01"
get-mailbox | get-mailboxstatistics | select-object DisplayName,TotalItemSize,StorageLimitStatus,LastLogonTime
Get-MailboxStatistics -database "Your-Mailbox-BDD01" | Select DisplayName, LastLoggedOnUserAccount, ItemCount, TotalItemSize, LastLogonTime, LastLogoffTime | Format-Table
Get-MailboxStatistics -Database "Your-Mailbox-BDD01" | Sort -Property TotalItemsize | Format-Table DisplayName, LastLoggedOnUserAccount, ItemCount, @{expression={$_.totalitemsize.value.ToMB()};label="Size(MB)"}, LastLogonTime, LastLogoffTime
Get-MailboxStatistics -Database "mailbox database" | Sort -Property DisplayName | ft DisplayName, @{expression={$_.totalitemsize.value.ToMB()};label="Mailbox Size(MB)"}, itemcount, lastlogontime, lastlogofftime,lastloggedonuseraccount
Affecter les quotas des boites aux lettres par défaut pour une bases de données :
set-MailboxDatabase "Your-Mailbox-BDD03" -ProhibitSendReceiveQuota 50GB -ProhibitSendQuota 45GB -IssueWarningQuota 40GB
Attention, ci dessous les tailles sont en octets!!!
Set-MailboxDatabase "Your-Mailbox-BDD02" -IssueWarningQuota 40000000 -ProhibitSendQuota 50000000 -ProhibitSendReceiveQuota 50000000
Supprimer la rétention d'éléments pour toutes les bases de données d'un serveur spécifié :
Get-MailboxDatabase -Server <Server Name> | Set-MailboxDatabase -ItemRetention 45.00:00:00
Appliquer des limites de rétention d'éléments supprimés ou de rétention de boîtes aux lettres à tous les serveurs de l'organisation :Set-MailboxDatabase "Your-Mailbox-BDD02" -DeletedItemRetention 7.00:00:00 -MailboxRetention 10.00:00:00 -RetainDeletedItemsUntilBackup $true
Get-MailboxDatabase | Set-MailboxDatabase -ItemRetention 45.00:00:00 -MailboxRetention 120.00:00:00
Déplacement des journaux de transactions:
Move-StorageGroupPath -identity SERVER\Name of the StorageGroup -LogFolderPath X:\PathToLogFiles -SystemFolderPath X:\SystemFolderPath
Déplacement d'une base de données :
Move-DatabasePath Server\StorageGroup\MailboxStore -EDBFilePath X:\PathToDatabase
Comment changer la langue d’une Boîte aux lettres :
Pour définir le langage de la boîte aux lettres de Pierre Durant à Francais, exécutez la commande suivante :
Set-Mailbox - Identity “Pierre Durant” - Languages “fr-FR” •
Pour ajouter le langage Anglais à la boîte aux lettres de Pierre Durant sans écraser les langues déjà définies, il faut exécuter les commandes suivantes:
$Mailbox = Get-Mailbox - Identity “Pierre Durant”
$Mailbox.Languages += “en-US”
Set-Mailbox - Authority $Mailbox
Gestion des boîtes aux lettres des utilisateurs :
Taille des bals par Bases
Get-MailboxStatistics -database "Your-Mailbox-BDD01" | Format-Table
Get-MailboxStatistics -database "Your-Mailbox-BDD02" | Format-Table
Get-MailboxStatistics -database “Your-Mailbox-BDD01” | Select DisplayName, LastLoggedOnUserAccount, ItemCount, TotalItemSize, LastLogonTime, LastLogoffTime | Format-Table
Get-MailboxStatistics -Database “Your-Mailbox-BDD01” | Sort -Property TotalItemsize | Format-Table DisplayName, LastLoggedOnUserAccount, ItemCount, @{expression={$_.totalitemsize.value.ToMB()};label=”Size(MB)”}, LastLogonTime, LastLogoffTime
Get-MailboxStatistics -Database “Mailbox Database” | Select DisplayName, LastLoggedOnUserAccount, ItemCount, TotalItemSize, LastLogonTime, LastLogoffTime | Export-CSV test.csv
Identifier la taille des bals par entité (Users,alias, …) :
Get-MailboxStatistics -Identity xxxxx
Exemple : Get-MailboxStatistics -Identity Digueye2
Recherche d'utilidateur répondant à des critères spécifiques :
Get-User -Filter { Title -like '*executive*' }
Modifier les quotas d'une boîte aux lettres :
Set-Mailbox Mailbox1 -ProhibitSendQuota 200mb
Application de modification sur une série filtrée de boîtes aux lettres :
Get-User -Filter { Title -like '*executive' } | Set-Mailbox -ProhibitSendQuota 200mb
Déplacer une boîte aux lettres vers une autre base de données :
Move-Mailbox contoso\john -TargetDatabase "First Storage Group\Mailbox Database" -BadItemLimit 5 -MailboxSizeLimitOptions PreserveSource -MaxThreads 6 -SourceMailboxCleanupOptions DeleteSourceMailbox
Activer le forward vers une autre adresse SMTP sur une boîte aux lettres :
Set-Mailbox -Identity "John Smith" -ForwardingAddress "sara@contoso.com" -DeliverToMailboxAndForward $true
Connaître les autorisations attribuées à un compte d'utilisateur Active Directory sur une boîte aux lettres spécifique :
Get-Mailbox <Mailbox to Check> | Get-MailboxPermission -User <Active Directory User>
Accorder les autorisations "Envoyer pour" à un utilisateur sur une BAL autre que la sienne :
Le paramètre Identité requiert le nom complet de l’utilisateur entre guillemets.
Dans l'exemple ci-dessous, le propriétaire de la boîte aux lettres est Elen Adam. Les droits Envoyer pour (Send as) sont attribuer à Ted Bremer
Add-ADPermission -Identity "Ellen Adams" -User TedBrem -AccessRights extendedright -ExtendedRights "send as"
Accorder les autorisations "Receive as" à un utilisateur sur toutes les BALS d'une base :
Add-ADPermission –identity "mailbox database" –user "serviceaccount" –ExtendedRights Receive-As
Donner les droits d'accès complet à un utilisateur sur une BAL autre que la sienne :
Ci-dessous, les droits d'accès complets sont octroyés à User2 sur la BAL de User1
Add-MailboxPermission -Identity User1 –User User2 –AccessRights FullAccess
Donner les droits d’accès sur toutes les mailbox :
IMPORTANT : penser à retirer le compte de tous les groupes qui ont un Deny explicite sur l’accès aux Bals (exemple ; Admins du domaine, Exchange Administrators,…)
Lancer : Get-Mailbox -resultsize unlimited | add-mailboxpermission -user compte -accessrights fullaccess -InheritanceType All
Ou bien :
Get-Mailbox -resultsize unlimited | Add-AdPermission -user compte -accessRights GenericAll -extendedrights "Receive as","Send as"
Afficher les droits d'accès à une BAL spécifique :
Get-MailboxPermission -identity "testar" -user "administrateurs de l'entreprise"
Get-MailboxPermission -identity "testar" -user "admins du domaine"
Get-MailboxPermission -identity "testar" -user "Exchange Organization Administrators"
Identity User AccessRights IsInherited Deny
-------- ---- ------------ ----------- ----
YourInternalDomain.example/TestAR YOURADDOMAIN\Exchang... {FullAccess} True True
YourInternalDomain.example/TestAR YOURADDOMAIN\Exchang... {FullAccess, DeleteItem, ReadPermission, ChangePermission, ChangeOwner} True False
Get-MailboxPermission -identity "testar" -user "Exchange Domain Servers"
Identity User AccessRights IsInherited Deny
-------- ---- ------------ ----------- ----
YourInternalDomain.example/TestAR YOURADDOMAIN\Exchang... {FullAccess} True False
YourInternalDomain.example/TestAR YOURADDOMAIN\Exchang... {ReadPermission} True False
Récupérer dans un fichier les permissions sur une BAL (exemple: BAL = testar) :
get-mailboxpermission -Identity "Blin Aurélie"| format-list| out-file C:\permission-on-testar.txt
get-mailboxpermission -Identity "Blin Aurélie" | where {$_.Deny -eq $True}| format-list
Récupérer dans un fichier les permissions sur le compte AD associé à la BAL :
get-ADpermission -identity testar | format-list| out-file C:\permission-on-testar.txt
Récupérer les permissions d'un utilisateur ou d'un groupe spécifique sur les objets d'une base de données Exchange spécifique :
Get-ADPermission -identity "Your-Mailbox-BDD01" -user "Experts"
Identity User Deny Inherited Rights
-------- ---- ---- --------- ------
SRVMAIL\First Sto... YOURADDOMAIN\experts False True GenericAll
Get-ADPermission -identity "Your-Mailbox-BDD01" -user "arsystemes"
Identity User Deny Inherited Rights
-------- ---- ---- --------- ------
YourSRV\First Sto... YOURADDOMAIN\arsystemes True True Send-As
YourSRV\First Sto... YOURADDOMAIN\arsystemes True True Receive-As
YourSRV\First Sto... YOURADDOMAIN\arsystemes False True GenericAll
Récupérer les permissions d'un utilisateur ou d'un groupe spécifique sur les objets de l'organisation Exchange complêteGet-ADPermission -identity "CG28" -user "arsystemes"
Identity User Deny Inherited Rights
-------- ---- ---- --------- ------
YourDomaine YOURADDOMAIN\arsystemes True False Receive-As
YourDomaine YOURADDOMAIN\arsystemes True False Send-As
YourDomaine YOURADDOMAIN\arsystemes False False GenericAll
YourDomaine YOURADDOMAIN\arsystemes False True GenericAll
Get-ADPermission -identity "CG28" -user "Experts"
Identity User Deny Inherited Rights
-------- ---- ---- --------- ------
CG28 YOURADDOMAIN\experts False False GenericAll
Savoir sur quelles boîtes aux lettres un utilisateur Active Directory spécifique à des autorisations ;
Get-Mailbox -ResultSize Unlimited | Get-MailboxPermission -User <Active Directory User> | Format-Table Identity, AccessRights, Deny
Comment afficher la propriété Name de chaque objet boîte aux lettres transmis via le pipeline :
Get-Mailbox | ForEach { $_.Name }
Exporter des données de boîte aux lettres directement dans un fichier .pst :
Utilisez la cmdlet Export-Mailbox. Vous pouvez même exporter plusieurs boîtes aux lettres à l'aide d'une seule commande:
Get-Mailbox | Export-Mailbox -PSTFolderPath <path to folder where data will be exported>
Vous pouvez également importer des fichiers .pst dans des boîtes aux lettres à l'aide de la cmdlet Import-Mailbox :
Get-Mailbox | Import-Mailbox -PSTFolderPath <path to folder with <alias>.pst files to import>
Modifier les droits d'administration Exchange :
Add-ExchangeAdministrator -Role OrgAdmin -Identity Contoso\Ted
Add-ExchangeAdministrator -Role ServerAdmin -Identity Contoso\Iliana -Scope Contoso-Mail-01
Get-mailboxserver srvmail | add-exchangeadministrator BESAdmin –role ViewOnlyAdmin
Remove-ExchangeAdministrator -Identity Administrator -Role OrgAdmin
Commande en Pipe-Line pour affecter des droits spécifiques :
get-mailboxserver srvmail | add-adpermission -user adminbes -accessrights GenericRead, GenericWrite -extendedrights Send-As, Receive-As, ms-Exch-Store-Admin
Pour vérifier:
get-adpermission -Identity <Organisation-Name> -user adminbes
get-adpermission -Identity CG28 -user adminbes
get-adpermission -identity <serveur-de-mail> -user adminbes
get-adpermission -identity srvmail -user adminbes
Récupérer une boîte aux lettres d'un utilisateur existant :
Restore-Mailbox can also recover data of users that have an active mailbox in the Exchange Organization. The way to do this is to recover the backup to the RSG database, and from there restore the user’s mailbox (or part of it using filtering) by simply specifying the ID for the mailbox to be restored. In this case, source and target should be the same so there is no need to use RSGMailbox.
Après avoir restauré une sauvegarde dans le Recovery Storage group:
- restore all RSG content of mailbox testE12mbx1 to the currently used testE12mbx1 mailbox:
- restore all RSG content sent between 02/02/05 and 02/05/05 of mailbox testE12mbx1 to the currently used testE12mbx1 mailbox:
- restore all RSG mailboxes to their currently active mailbox counterparts:
- restore all RSG content of mailbox testE12mbx1 to a folder called Backup inside the currently used testE12mbx2 mailbox:
- all RSG content of mailbox testE12mbx1 to a folder called Backup inside the currently used testE12mbx2 mailbox:
- An administrator wants to restore email content from a RSG mailbox into a folder inside a currently active mailbox - restore all RSG content of mailbox testE12mbx1 to a folder called Backup inside the currently used testE12mbx2 mailbox:
- restore all RSG content sent between 02/02/05 and 02/05/05 of mailbox testE12mbx1 to a folder called Backup inside the currently used testE12mbx2 mailbox
- restore all RSG mailboxes to a folder called DatabaseBackup inside mailbox testE12mbx2:
- restore all RSG content of mailbox testE12mbx1 to the currently used testE12mbx1 mailbox:
- restore all RSG mailboxes to their currently active mailbox counterparts
- restore all RSG content of mailbox testE12mbx1 to the currently used testE12mbx1 mailbox
- restore all RSG mailboxes to their currently active mailbox counterparts:
Création d'un groupe de distribution pour tous les utilisateurs via EMS :
Utilisation d'un Dynamic Distribution GroupThis is the easiest and most fool-proof way to do it. You simply create a dynamic distribution group that has a custom recipient filter.
New-DynamicDistributionGroup -Name "Server1 Users" -OrganizationalUnit Users -RecipientFilter "((RecipientType -eq 'MailboxUser' -and ServerName -eq 'Server1') -and -not(Name -like 'SystemMailbox{*'))"
The first part of the recipient filter string tells the dynamic distribution group to only get recipients of type "MailboxUser" that have their ServerName parameter equal to Server1. The second part of the recipient filter filters out the system mailboxes.
Utilisation d'un Distribution Group régulier :
If you don't want to use dynamic distribution groups, you can accomplish the same result by filtering the results of the Get-Mailbox cmdlet and pipelining the output to the Add-DistributionGroupMember cmdlet.
First, let's create a distribution group:
New-DistributionGroup -Type Distribution -SamAccountName "Server1 Users" -Name "Server1 Users" -OrganizationalUnit "Users"
Now we can use the Get-Mailbox cmdlet to return all mailboxes in the organization that reside on the server "Server1". We can pipeline the output of the Get-Mailbox cmdlet to the Add-DistributionGroupMember cmdlet:
Get-Mailbox -Filter "ServerName -eq 'Server1'" | Add-DistributionGroupMember -Identity "Server1 Users"
The distribution group "Server1 Users" now has all the mailboxes that are hosted on server "Server1".
A REALISER DANS LE CADRE D'UNE MIGRATION D'EXCHANGE 2003 VERS 2007 .....
Modification des récipients pour Exchange 2007 :
Recipient objects in Exchange 2007 fall under a more strict "validation" scheme than they did in previous versions of Exchange. This means that if some property is incorrect or missing on the recipient object, there is higher-level logical enforcement that this property must be corrected before the object will successfully validate as being in a good state. If a recipient object does not successfully validate when it is read from the AD, a warning will be reported to detail the cause of the failure(s). It may also prevent the action you were attempting, such as: moving the mailbox, saving other properties to the recipient object, etc until the object passes validation.
Voir ci-après pour les correxctiuons à apporter dans le détails
Vérifier et correction lorsque le nom affiché d'un utilisateur (Display name) à des espaces :
Ceci était toléré avant Exchange 2007 mais ne l'est plus.
WARNING: Object Domain.com/Users/TestUser has been corrupted and it is in an inconsistent state. The following validation errors have been encountered:
WARNING: The DisplayName property contains leading or trailing whitespace, which must be removed.
This can be fixed by "trimming" the invalid whitespace from the displayname
Get-Mailbox | Foreach { Set-Mailbox –Identity $_.Id –DisplayName $_.DisplayName.Trim() }
Vérification et suppression des espace aux niveau des alias de BAL (mailnickname)Identify all recipients with this issue with a simple LDAP query - (&(objectclass=*)(mailnickname=* *))
Pour supprimer les espace sur les BAL, Contacts ou Distribution Lists :
Get-Mailbox | Where {$_.Alias -like "* *"} | ForEach-Object {Set-Mailbox $_.Name -Alias:($_.Alias -Replace " ","")}
Get-Contact | Where {$_.Alias -like "* *"} | ForEach-Object {Set-Contact $_.Name -Alias:($_.Alias -Replace " ","")}
Get-DistributionGroup | Where {$_.Alias -like "* *"} | ForEach-Object {Set-DistributionGroup $_.Name -Alias:($_.Alias -Replace " ","")}
Correction des Extension Attributes: PSH and AD Schema Conflict :
WARNING: Object fwf.net/Operations/User Test01. User has been corrupted and it is in an inconsistent state. The following validation errors have been encountered:
WARNING: CustomAttribute15 is too long: maximum length is 2048, actual length is 2500.
Extension Attributes are renamed back to Custom Attributes in PSH. PSH does not reference the AD schema for attribute properties, it uses its own lookup table. Therefore, even if the AD schema has been manually modified to allow greater than 2048 length for a "Custom Attribute" value, PSH will mark the recipient using this larger size as invalid. This maximum length was changed in Beta builds from 1024 to 2048, but does not reference the AD schema size definition if has been customized.
Modification des EAP (Email Address Policy) pour Exchange 2007 :
Pour contrôler:
Get-EmailAddressPolicy | Format-List Name,*RecipientFilter*,ExchangeVersion
Get-EmailAddressPolicy | where { $_.RecipientFilterType -eq "Legacy" }
Pour les modifier et rendre conforme à Exchange 2007:
Set-EmailAddressPolicy "Default Policy" -IncludedRecipients AllRecipients
Modification des listes d'adresses pour Exchange 2007 :
Pour contrôler:
Get-AddressList | Format-List Name,*RecipientFilter*,ExchangeVersion
Get-GlobalAddressList | Format-List Name,*RecipientFilter*,ExchangeVersion
Pour modifier et rendre conforme à Exchange 2007:
Set-AddressList "All Users" -IncludedRecipients MailboxUsers
Set-AddressList "Tous les utilisateurs" -IncludedRecipients MailboxUsers
Set-AddressList "Tous les contacts" -IncludedRecipients MailContacts
Set-AddressList "Dossiers publics" -RecipientFilter { RecipientType -eq 'PublicFolder' }
Set-GlobalAddressList "Liste d'adresses globale par défaut" -RecipientFilter {(Alias -ne $null -and (ObjectClass -eq 'user' -or ObjectClass -eq 'contact' -or ObjectClass -eq 'msExchSystemMailbox' -or ObjectClass -eq 'msExchDynamicDistributionList' -or ObjectClass -eq 'group' -or ObjectClass -eq 'publicFolder'))}
Déplacer la gestion de l'OAB vers un autre serveur :
Déplacer la gestion du carnet d’adresse en mode autonome vers le nouveau serveur Exchange 2007
Move-OfflineAddressBook -Identity "My OAB" -Server Your-Exchange-Server
######################################################################################################
Retour...