Question
Mail de bienvenue
- leroy
- Auteur du sujet
- Hors Ligne
- Nouveau membre
-
Réduire
Plus d'informations
- Messages : 6
- Remerciements reçus 0
il y a 12 ans 9 mois #14892
par leroy
Mail de bienvenue a été créé par leroy
Bonjour,
Je suis novice dans le powershell, mais dans le cadre d'un projet dans mon entreprise, j'ai été amené à me pencher dessus.
Je dois faire un script qui envoie un template défini par mail à chaque BAL récemment créée. Cette partie est ok (j'ai trouver un tuto microsoft qui propose une fonctione qui fait tout le boulot).
Mon problème est le suivant :
Je souhaite personnaliser ce script de manière à ce qu'il test si il s'agit d'un utilisateur FR ou bien autre nationnalité, et qu'il envoie le template FR dans le 1er cas, ou bien le template EN dans tous les autre cas.
Voici le script (ou plutot la fonction) proposée par microsoft (je ne l'ai pas modifiée) :
[code:1]<#
The sample scripts are not supported under any Microsoft standard support
program or service. The sample scripts are provided AS IS without warranty
of any kind. Microsoft further disclaims all implied warranties including,
without limitation, any implied warranties of merchantability or of fitness for
a particular purpose. The entire risk arising out of the use or performance of
the sample scripts and documentation remains with you. In no event shall
Microsoft, its authors, or anyone else involved in the creation, production, or
delivery of the scripts be liable for any damages whatsoever (including,
without limitation, damages for loss of business profits, business interruption,
loss of business information, or other pecuniary loss) arising out of the use
of or inability to use the sample scripts or documentation, even if Microsoft
has been advised of the possibility of such damages.
#>
#requires -Version 2
#Import Localized Data
Import-LocalizedData -BindingVariable Messages
Function New-OSCPSCustomErrorRecord
{
#This function is used to create a PowerShell ErrorRecord
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true,Position=1)][String]$ExceptionString,
[Parameter(Mandatory=$true,Position=2)][String]$ErrorID,
[Parameter(Mandatory=$true,Position=3)][System.Management.Automation.ErrorCategory]$ErrorCategory,
[Parameter(Mandatory=$true,Position=4)][PSObject]$TargetObject
)
Process
{
$exception = New-Object System.Management.Automation.RuntimeException($ExceptionString)
$customError = New-Object System.Management.Automation.ErrorRecord($exception,$ErrorID,$ErrorCategory,$TargetObject)
return $customError
}
}
Function Send-OSCEXWelcomeMail
{
<#
.SYNOPSIS
Send-OSCEXWelcomeMail is an advanced function which can be used to send welcome mail to each newly created mailbox in Microsoft Exchange 2010.
.DESCRIPTION
Send-OSCEXWelcomeMail is an advanced function which can be used to send welcome mail to each newly created mailbox in Microsoft Exchange 2010.
It allows you to use an .html file as a template. You can use placeholders in this template file, it will help you to replace these placeholders when the script is being executed.
.PARAMETER MailboxFilter
Indicates the OPath filter used to find mailboxes. You can user additional filter to find newly created mailboxes.
This function will combine these filters with the one which will be used to find newly created mailboxes.
.PARAMETER ScheduledTaskRepeatInterval
Indicates the repeat interval(in minutes) of the scheduled task. This value will also be used to generate the filter for Get-Mailbox cmdlet.
If you use 2 hours as the repeat interval of the scheduled task, you should use 120 as the value of this parameter.
.PARAMETER From
Indicates the mail address from which the mail is sent, in the form Cette adresse e-mail est protégée contre les robots spammeurs. Vous devez activer le JavaScript pour la visualiser.
.PARAMETER Subject
Indicates the subject of the e-mail message.
.PARAMETER SMTPServer
Indicates the name of the SMTP server that sends the e-mail message.
For a Exchange Hub Transport server,you should create a receive connector to allow anonymous relay.
.PARAMETER Encoding
Indicates the encoding used for the mail body and subject.
.PARAMETER Template
Indicates the path of an .html file which will be used as a mail template.You can use placeholders in this template file.
.PARAMETER Credential
Specifies a user account that has permission to perform this action.
.PARAMETER ReplacePlaceholders
Indicates the placeholders which will be replaced, in the form @{\"Placeholder01\"=\"RealValue01\";\"Placeholder02\"=\"RealValue02\"}
You can use any other string rather than Placeholder##.
.PARAMETER RecycleLog
Indicates this function will remove old sent entries in the log file.
.PARAMETER AdminEmailAddress
Indicates the email address of an administrator.
It also indicates the script is running in pilot mode, which means welcome mails will not be sent to the newly created mailboxes.
These welcome mails will be redirected to the administrator's mailbox.
.EXAMPLE
#Send welcome mails to these mailboxes which created four hours before the script is being executed. (In pilot mode)
Send-OSCEXWelcomeMail -ScheduledTaskRepeatInterval 240 -From \"itadmin@corp.contoso.com\" -Subject \"Welcome to Contoso!\" -SMTPServer \"smtpserver.corp.contoso.com\" `
-Template \"c:\Scripts\029\MailTemplate.html\" -RecycleLog -AdminEmailAddress \"itadmin@corp.contoso.com\" -Verbose
.EXAMPLE
#Send welcome mails to these mailboxes which created four hours before the script is being executed.
Send-OSCEXWelcomeMail -ScheduledTaskRepeatInterval 240 -From \"itadmin@corp.contoso.com\" -Subject \"Welcome to Contoso!\" -SMTPServer \"smtpserver.corp.contoso.com\" `
-Template \"c:\Scripts\029\MailTemplate.html\" -RecycleLog -Verbose
.EXAMPLE
#Send welcome mails to these mailboxes which created four hours before the script is being executed. The encoding which will be used is Unicode.
Send-OSCEXWelcomeMail -ScheduledTaskRepeatInterval 240 -From \"itadmin@corp.contoso.com\" -Subject \"Welcome to Contoso!\" -SMTPServer \"smtpserver.corp.contoso.com\" `
-Template \"c:\Scripts\029\MailTemplate.html\" -RecycleLog -AdminEmailAddress \"itadmin@corp.contoso.com\" -Encoding ([System.Text.ASCIIEncoding]::Unicode) -Verbose
.EXAMPLE
#Send welcome mails to these mailboxes which CustomAttribute1 is ITO. The mailboxes are created two hours before the script is being executed.
#Replace Placeholder01 which contains in the template file with the real department name.
Send-OSCEXWelcomeMail -MailboxFilter 'CustomAttribute1 -eq \"ITO\"' -ScheduledTaskRepeatInterval 120 -From \"itadmin@corp.contoso.com\" -Subject \"Welcome to Contoso!\" -SMTPServer \"smtpserver.corp.contoso.com\" `
-Template \"c:\Scripts\029\MailTemplate.html\" -RecycleLog -ReplacePlaceholders @{\"Placeholder01\"=\"ITO department\"} -Verbose
.LINK
Windows PowerShell Advanced Function
technet.microsoft.com/en-us/library/dd315326.aspx
.LINK
Get-Mailbox
technet.microsoft.com/en-us/library/bb123685.aspx
.LINK
Filterable Properties for the -Filter Parameter in Exchange 2007 SP1 and SP2
technet.microsoft.com/en-us/library/bb738155(v=exchg.80).aspx
.LINK
Scripting with the Exchange Management Shell
technet.microsoft.com/en-us/library/bb123798.aspx
.LINK
Understanding Role Based Access Control
technet.microsoft.com/en-us/library/dd298183.aspx
#>
[CmdletBinding(DefaultParameterSetName=\"__AllParameterSets\"«»)]
Param
(
#Define parameters
[Parameter(Mandatory=$false,Position=1)]
[string]$MailboxFilter,
[Parameter(Mandatory=$true,Position=2)]
[int]$ScheduledTaskRepeatInterval,
[Parameter(Mandatory=$true,Position=3)]
[string]$From,
[Parameter(Mandatory=$true,Position=4)]
[string]$Subject,
[Parameter(Mandatory=$true,Position=5)]
[string]$SMTPServer,
[Parameter(Mandatory=$false,Position=6)]
[PSObject]$Encoding,
[Parameter(Mandatory=$true,Position=7)]
[string]$Template,
[Parameter(Mandatory=$false,Position=8)]
[System.Management.Automation.PSCredential]$Credential,
[Parameter(Mandatory=$false,Position=9)]
[hashtable]$ReplacePlaceholders,
[Parameter(Mandatory=$false,Position=10)]
[switch]$RecycleLog,
[Parameter(Mandatory=$true,Position=11,ParameterSetName=\"Pilot\"«»)]
[string]$AdminEmailAddress
)
Process
{
$sentUsers = @{}
$scriptName = $pscmdlet.MyInvocation.ScriptName
$scriptLogDirectory = (Get-ChildItem -Path $scriptName).Directory
$scriptLogFile = \"$scriptLogDirectory\SentLog.csv\"
$startDate = (Get-Date).AddMinutes(-$ScheduledTaskRepeatInterval)
#Get sent history
#If sent history does not exist, create the sent history log file.
if (-not (Test-Path -Path $scriptLogFile -PathType Leaf)) {
Out-File -FilePath $scriptLogFile -InputObject \"`\"Alias`\",`\"WhenSent`\"\" -Encoding Unicode
} else {
#If RecycleLog is $true, this function will keep the latest sent history after the script is executed.
if($RecycleLog) {
Remove-Item -Path $scriptLogFile
Out-File -FilePath $scriptLogFile -InputObject \"`\"Alias`\",`\"WhenSent`\"\" -Encoding Unicode
} else {
$rawEntries = Import-Csv -Path $scriptLogFile
}
}
#Get sent history
if ($rawEntries -ne $null) {
foreach ($rawEntry in $rawEntries) {
$sentUsers.Add($rawEntry.Alias,$rawEntry.WhenSent)
}
}
#Get welcome mail template
if (-not (Test-Path -Path $Template -PathType Leaf)) {
#Cannot find welcome mail template
$errorMsg = $Messages.CannotFindWelcomeMailTemplate
$errorMsg = $errorMsg -f $Template
$customError = New-OSCPSCustomErrorRecord `
-ExceptionString $errorMsg `
-ErrorCategory NotSpecified -ErrorID 1 -TargetObject $pscmdlet
$pscmdlet.ThrowTerminatingError($customError)
} else {
#Get welcome mail body.
$welcomeMailBody = [string](Get-Content $Template)
}
#Replace any placeholders with real values
if ($ReplacePlaceholders -ne $null) {
foreach ($placeholders in $ReplacePlaceholders.GetEnumerator())
{
$welcomeMailBody = $welcomeMailBody -replace $($placeholders.Key),$($placeholders.Value)
}
}
#Get newly created mailboxes
if (-not [System.String]::IsNullOrEmpty($MailboxFilter)) {
$mbxFilter = \"($MailboxFilter) -and (whenCreated -gt `\"$startDate`\"«»)\"
} else {
$mbxFilter = \"(whenCreated -gt `\"$startDate`\"«»)\"
}
$verboseMsg = $Messages.DisplayMailboxFilter
$verboseMsg = $verboseMsg -f $mbxFilter
$pscmdlet.WriteVerbose($verboseMsg)
$newlyCreatedMailboxes = Get-Mailbox -Filter $mbxFilter -ResultSize unlimited -Verbose:$false
#Send welcome mail to each newly created mailbox.
if ($newlyCreatedMailboxes -ne $null) {
foreach ($newlyCreatedMailbox in $newlyCreatedMailboxes) {
$newlyCreatedMailboxAlias = $newlyCreatedMailbox.Alias
$newlyCreatedMailboxDisplayName = $newlyCreatedMailbox.DisplayName
$mailBody = $welcomeMailBody -replace \"Placeholder00\",$newlyCreatedMailboxDisplayName
#Avoid sending duplicate welcome mails in a specific time period if the value of RecylceLog is $true.
#For example, the script is executed in 01:10 PM, the value of ScheduledTaskRepeatInterval is 10.
#This function checks the mailboxes which are created between 01:00 PM to 01:10 PM.
#If the script is executed multiple times in this time period(manually by an administrator), only one welcome mail will be sent the user.
#If the value of RecylceLog is $false, this function will not send welcome mails to the mailboxes which are listed in the sent history.
if ($sentUsers.ContainsKey($newlyCreatedMailboxAlias)) {
$verboseMsg = $Messages.WelcomeMailHasBeenSentAlready
$verboseMsg = $verboseMsg -f $newlyCreatedMailboxAlias
$pscmdlet.WriteVerbose($verboseMsg)
} else {
Switch ($pscmdlet.ParameterSetName) {
\"__AllParameterSets\" {
#Send welcome mail to one employee
$verboseMsg = $Messages.SendingWelcomeMail
$verboseMsg = $verboseMsg -f $newlyCreatedMailboxAlias
$pscmdlet.WriteVerbose($verboseMsg)
if ($Credential -ne $null) {
Send-MailMessage -From $From -To $($newlyCreatedMailbox.PrimarySmtpAddress) `
-Subject $Subject -Body $mailBody -BodyAsHtml `
-SmtpServer $SMTPServer -Credential $Credential
} else {
Send-MailMessage -From $From -To $($newlyCreatedMailbox.PrimarySmtpAddress) `
-Subject $Subject -Body $mailBody -BodyAsHtml `
-SmtpServer $SMTPServer
}
#Write user alias and mail sent time to the log file
Out-File -FilePath $scriptLogFile -InputObject \"`\"$newlyCreatedMailboxAlias`\",`\"$(Get-Date)`\"\" -Append -Encoding Unicode
}
\"Pilot\" {
#Redirect welcome mail to administrator
$verboseMsg = $Messages.RedirctingWelcomeMail
$verboseMsg = $verboseMsg -f $newlyCreatedMailboxAlias,$AdminEmailAddress
$pscmdlet.WriteVerbose($verboseMsg)
if ($Credential -ne $null) {
Send-MailMessage -From $From -To $AdminEmailAddress `
-Subject $Subject -Body $mailBody -BodyAsHtml `
-SmtpServer $SMTPServer -Credential $Credential
} else {
Send-MailMessage -From $From -To $AdminEmailAddress `
-Subject $Subject -Body $mailBody -BodyAsHtml `
-SmtpServer $SMTPServer
}
}
}
}
}
} else {
$warningMsg = $Messages.CannotFindAnyNewlyCreatedMBX
$pscmdlet.WriteWarning($warningMsg)
}
}
}
[/code:1]
Et maintenant ma partie :
$toto = $newlyCreatedMailboxAlias.DistinguishedName
if ($toto -Match \"OU=FR\") {
Send-OSCEXWelcomeMail -ScheduledTaskRepeatInterval 240 -From \"CommunicationDOSI@XXXX.fr\" -Subject \"Welcome !\" -SMTPServer \"XX.XX.XX.XX\" -Template \"c:\script\Welcome mail\Template_FR.html\" -Verbose
} else {
Send-OSCEXWelcomeMail -ScheduledTaskRepeatInterval 240 -From \"CommunicationDOSI@XXXX.fr\" -Subject \"Welcome !\" -SMTPServer \"XX.XX.XX.XX\" -Template \"c:\script\Welcome mail\Template_EN.html\" -Verbose
}
Le problème je pense est le suivant : l'assignation du contenu $newlyCreatedMailboxAlias.DistinguishedName dans la variable $toto.
Pouvez vous m'aider svp ?
Merci d'avance,
Cordialement,
TOR
Message édité par: TOR, à: 22/05/13 11:21<br><br>Message édité par: TOR, à: 27/05/13 16:41
Je suis novice dans le powershell, mais dans le cadre d'un projet dans mon entreprise, j'ai été amené à me pencher dessus.
Je dois faire un script qui envoie un template défini par mail à chaque BAL récemment créée. Cette partie est ok (j'ai trouver un tuto microsoft qui propose une fonctione qui fait tout le boulot).
Mon problème est le suivant :
Je souhaite personnaliser ce script de manière à ce qu'il test si il s'agit d'un utilisateur FR ou bien autre nationnalité, et qu'il envoie le template FR dans le 1er cas, ou bien le template EN dans tous les autre cas.
Voici le script (ou plutot la fonction) proposée par microsoft (je ne l'ai pas modifiée) :
[code:1]<#
The sample scripts are not supported under any Microsoft standard support
program or service. The sample scripts are provided AS IS without warranty
of any kind. Microsoft further disclaims all implied warranties including,
without limitation, any implied warranties of merchantability or of fitness for
a particular purpose. The entire risk arising out of the use or performance of
the sample scripts and documentation remains with you. In no event shall
Microsoft, its authors, or anyone else involved in the creation, production, or
delivery of the scripts be liable for any damages whatsoever (including,
without limitation, damages for loss of business profits, business interruption,
loss of business information, or other pecuniary loss) arising out of the use
of or inability to use the sample scripts or documentation, even if Microsoft
has been advised of the possibility of such damages.
#>
#requires -Version 2
#Import Localized Data
Import-LocalizedData -BindingVariable Messages
Function New-OSCPSCustomErrorRecord
{
#This function is used to create a PowerShell ErrorRecord
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true,Position=1)][String]$ExceptionString,
[Parameter(Mandatory=$true,Position=2)][String]$ErrorID,
[Parameter(Mandatory=$true,Position=3)][System.Management.Automation.ErrorCategory]$ErrorCategory,
[Parameter(Mandatory=$true,Position=4)][PSObject]$TargetObject
)
Process
{
$exception = New-Object System.Management.Automation.RuntimeException($ExceptionString)
$customError = New-Object System.Management.Automation.ErrorRecord($exception,$ErrorID,$ErrorCategory,$TargetObject)
return $customError
}
}
Function Send-OSCEXWelcomeMail
{
<#
.SYNOPSIS
Send-OSCEXWelcomeMail is an advanced function which can be used to send welcome mail to each newly created mailbox in Microsoft Exchange 2010.
.DESCRIPTION
Send-OSCEXWelcomeMail is an advanced function which can be used to send welcome mail to each newly created mailbox in Microsoft Exchange 2010.
It allows you to use an .html file as a template. You can use placeholders in this template file, it will help you to replace these placeholders when the script is being executed.
.PARAMETER MailboxFilter
Indicates the OPath filter used to find mailboxes. You can user additional filter to find newly created mailboxes.
This function will combine these filters with the one which will be used to find newly created mailboxes.
.PARAMETER ScheduledTaskRepeatInterval
Indicates the repeat interval(in minutes) of the scheduled task. This value will also be used to generate the filter for Get-Mailbox cmdlet.
If you use 2 hours as the repeat interval of the scheduled task, you should use 120 as the value of this parameter.
.PARAMETER From
Indicates the mail address from which the mail is sent, in the form Cette adresse e-mail est protégée contre les robots spammeurs. Vous devez activer le JavaScript pour la visualiser.
.PARAMETER Subject
Indicates the subject of the e-mail message.
.PARAMETER SMTPServer
Indicates the name of the SMTP server that sends the e-mail message.
For a Exchange Hub Transport server,you should create a receive connector to allow anonymous relay.
.PARAMETER Encoding
Indicates the encoding used for the mail body and subject.
.PARAMETER Template
Indicates the path of an .html file which will be used as a mail template.You can use placeholders in this template file.
.PARAMETER Credential
Specifies a user account that has permission to perform this action.
.PARAMETER ReplacePlaceholders
Indicates the placeholders which will be replaced, in the form @{\"Placeholder01\"=\"RealValue01\";\"Placeholder02\"=\"RealValue02\"}
You can use any other string rather than Placeholder##.
.PARAMETER RecycleLog
Indicates this function will remove old sent entries in the log file.
.PARAMETER AdminEmailAddress
Indicates the email address of an administrator.
It also indicates the script is running in pilot mode, which means welcome mails will not be sent to the newly created mailboxes.
These welcome mails will be redirected to the administrator's mailbox.
.EXAMPLE
#Send welcome mails to these mailboxes which created four hours before the script is being executed. (In pilot mode)
Send-OSCEXWelcomeMail -ScheduledTaskRepeatInterval 240 -From \"itadmin@corp.contoso.com\" -Subject \"Welcome to Contoso!\" -SMTPServer \"smtpserver.corp.contoso.com\" `
-Template \"c:\Scripts\029\MailTemplate.html\" -RecycleLog -AdminEmailAddress \"itadmin@corp.contoso.com\" -Verbose
.EXAMPLE
#Send welcome mails to these mailboxes which created four hours before the script is being executed.
Send-OSCEXWelcomeMail -ScheduledTaskRepeatInterval 240 -From \"itadmin@corp.contoso.com\" -Subject \"Welcome to Contoso!\" -SMTPServer \"smtpserver.corp.contoso.com\" `
-Template \"c:\Scripts\029\MailTemplate.html\" -RecycleLog -Verbose
.EXAMPLE
#Send welcome mails to these mailboxes which created four hours before the script is being executed. The encoding which will be used is Unicode.
Send-OSCEXWelcomeMail -ScheduledTaskRepeatInterval 240 -From \"itadmin@corp.contoso.com\" -Subject \"Welcome to Contoso!\" -SMTPServer \"smtpserver.corp.contoso.com\" `
-Template \"c:\Scripts\029\MailTemplate.html\" -RecycleLog -AdminEmailAddress \"itadmin@corp.contoso.com\" -Encoding ([System.Text.ASCIIEncoding]::Unicode) -Verbose
.EXAMPLE
#Send welcome mails to these mailboxes which CustomAttribute1 is ITO. The mailboxes are created two hours before the script is being executed.
#Replace Placeholder01 which contains in the template file with the real department name.
Send-OSCEXWelcomeMail -MailboxFilter 'CustomAttribute1 -eq \"ITO\"' -ScheduledTaskRepeatInterval 120 -From \"itadmin@corp.contoso.com\" -Subject \"Welcome to Contoso!\" -SMTPServer \"smtpserver.corp.contoso.com\" `
-Template \"c:\Scripts\029\MailTemplate.html\" -RecycleLog -ReplacePlaceholders @{\"Placeholder01\"=\"ITO department\"} -Verbose
.LINK
Windows PowerShell Advanced Function
technet.microsoft.com/en-us/library/dd315326.aspx
.LINK
Get-Mailbox
technet.microsoft.com/en-us/library/bb123685.aspx
.LINK
Filterable Properties for the -Filter Parameter in Exchange 2007 SP1 and SP2
technet.microsoft.com/en-us/library/bb738155(v=exchg.80).aspx
.LINK
Scripting with the Exchange Management Shell
technet.microsoft.com/en-us/library/bb123798.aspx
.LINK
Understanding Role Based Access Control
technet.microsoft.com/en-us/library/dd298183.aspx
#>
[CmdletBinding(DefaultParameterSetName=\"__AllParameterSets\"«»)]
Param
(
#Define parameters
[Parameter(Mandatory=$false,Position=1)]
[string]$MailboxFilter,
[Parameter(Mandatory=$true,Position=2)]
[int]$ScheduledTaskRepeatInterval,
[Parameter(Mandatory=$true,Position=3)]
[string]$From,
[Parameter(Mandatory=$true,Position=4)]
[string]$Subject,
[Parameter(Mandatory=$true,Position=5)]
[string]$SMTPServer,
[Parameter(Mandatory=$false,Position=6)]
[PSObject]$Encoding,
[Parameter(Mandatory=$true,Position=7)]
[string]$Template,
[Parameter(Mandatory=$false,Position=8)]
[System.Management.Automation.PSCredential]$Credential,
[Parameter(Mandatory=$false,Position=9)]
[hashtable]$ReplacePlaceholders,
[Parameter(Mandatory=$false,Position=10)]
[switch]$RecycleLog,
[Parameter(Mandatory=$true,Position=11,ParameterSetName=\"Pilot\"«»)]
[string]$AdminEmailAddress
)
Process
{
$sentUsers = @{}
$scriptName = $pscmdlet.MyInvocation.ScriptName
$scriptLogDirectory = (Get-ChildItem -Path $scriptName).Directory
$scriptLogFile = \"$scriptLogDirectory\SentLog.csv\"
$startDate = (Get-Date).AddMinutes(-$ScheduledTaskRepeatInterval)
#Get sent history
#If sent history does not exist, create the sent history log file.
if (-not (Test-Path -Path $scriptLogFile -PathType Leaf)) {
Out-File -FilePath $scriptLogFile -InputObject \"`\"Alias`\",`\"WhenSent`\"\" -Encoding Unicode
} else {
#If RecycleLog is $true, this function will keep the latest sent history after the script is executed.
if($RecycleLog) {
Remove-Item -Path $scriptLogFile
Out-File -FilePath $scriptLogFile -InputObject \"`\"Alias`\",`\"WhenSent`\"\" -Encoding Unicode
} else {
$rawEntries = Import-Csv -Path $scriptLogFile
}
}
#Get sent history
if ($rawEntries -ne $null) {
foreach ($rawEntry in $rawEntries) {
$sentUsers.Add($rawEntry.Alias,$rawEntry.WhenSent)
}
}
#Get welcome mail template
if (-not (Test-Path -Path $Template -PathType Leaf)) {
#Cannot find welcome mail template
$errorMsg = $Messages.CannotFindWelcomeMailTemplate
$errorMsg = $errorMsg -f $Template
$customError = New-OSCPSCustomErrorRecord `
-ExceptionString $errorMsg `
-ErrorCategory NotSpecified -ErrorID 1 -TargetObject $pscmdlet
$pscmdlet.ThrowTerminatingError($customError)
} else {
#Get welcome mail body.
$welcomeMailBody = [string](Get-Content $Template)
}
#Replace any placeholders with real values
if ($ReplacePlaceholders -ne $null) {
foreach ($placeholders in $ReplacePlaceholders.GetEnumerator())
{
$welcomeMailBody = $welcomeMailBody -replace $($placeholders.Key),$($placeholders.Value)
}
}
#Get newly created mailboxes
if (-not [System.String]::IsNullOrEmpty($MailboxFilter)) {
$mbxFilter = \"($MailboxFilter) -and (whenCreated -gt `\"$startDate`\"«»)\"
} else {
$mbxFilter = \"(whenCreated -gt `\"$startDate`\"«»)\"
}
$verboseMsg = $Messages.DisplayMailboxFilter
$verboseMsg = $verboseMsg -f $mbxFilter
$pscmdlet.WriteVerbose($verboseMsg)
$newlyCreatedMailboxes = Get-Mailbox -Filter $mbxFilter -ResultSize unlimited -Verbose:$false
#Send welcome mail to each newly created mailbox.
if ($newlyCreatedMailboxes -ne $null) {
foreach ($newlyCreatedMailbox in $newlyCreatedMailboxes) {
$newlyCreatedMailboxAlias = $newlyCreatedMailbox.Alias
$newlyCreatedMailboxDisplayName = $newlyCreatedMailbox.DisplayName
$mailBody = $welcomeMailBody -replace \"Placeholder00\",$newlyCreatedMailboxDisplayName
#Avoid sending duplicate welcome mails in a specific time period if the value of RecylceLog is $true.
#For example, the script is executed in 01:10 PM, the value of ScheduledTaskRepeatInterval is 10.
#This function checks the mailboxes which are created between 01:00 PM to 01:10 PM.
#If the script is executed multiple times in this time period(manually by an administrator), only one welcome mail will be sent the user.
#If the value of RecylceLog is $false, this function will not send welcome mails to the mailboxes which are listed in the sent history.
if ($sentUsers.ContainsKey($newlyCreatedMailboxAlias)) {
$verboseMsg = $Messages.WelcomeMailHasBeenSentAlready
$verboseMsg = $verboseMsg -f $newlyCreatedMailboxAlias
$pscmdlet.WriteVerbose($verboseMsg)
} else {
Switch ($pscmdlet.ParameterSetName) {
\"__AllParameterSets\" {
#Send welcome mail to one employee
$verboseMsg = $Messages.SendingWelcomeMail
$verboseMsg = $verboseMsg -f $newlyCreatedMailboxAlias
$pscmdlet.WriteVerbose($verboseMsg)
if ($Credential -ne $null) {
Send-MailMessage -From $From -To $($newlyCreatedMailbox.PrimarySmtpAddress) `
-Subject $Subject -Body $mailBody -BodyAsHtml `
-SmtpServer $SMTPServer -Credential $Credential
} else {
Send-MailMessage -From $From -To $($newlyCreatedMailbox.PrimarySmtpAddress) `
-Subject $Subject -Body $mailBody -BodyAsHtml `
-SmtpServer $SMTPServer
}
#Write user alias and mail sent time to the log file
Out-File -FilePath $scriptLogFile -InputObject \"`\"$newlyCreatedMailboxAlias`\",`\"$(Get-Date)`\"\" -Append -Encoding Unicode
}
\"Pilot\" {
#Redirect welcome mail to administrator
$verboseMsg = $Messages.RedirctingWelcomeMail
$verboseMsg = $verboseMsg -f $newlyCreatedMailboxAlias,$AdminEmailAddress
$pscmdlet.WriteVerbose($verboseMsg)
if ($Credential -ne $null) {
Send-MailMessage -From $From -To $AdminEmailAddress `
-Subject $Subject -Body $mailBody -BodyAsHtml `
-SmtpServer $SMTPServer -Credential $Credential
} else {
Send-MailMessage -From $From -To $AdminEmailAddress `
-Subject $Subject -Body $mailBody -BodyAsHtml `
-SmtpServer $SMTPServer
}
}
}
}
}
} else {
$warningMsg = $Messages.CannotFindAnyNewlyCreatedMBX
$pscmdlet.WriteWarning($warningMsg)
}
}
}
[/code:1]
Et maintenant ma partie :
$toto = $newlyCreatedMailboxAlias.DistinguishedName
if ($toto -Match \"OU=FR\") {
Send-OSCEXWelcomeMail -ScheduledTaskRepeatInterval 240 -From \"CommunicationDOSI@XXXX.fr\" -Subject \"Welcome !\" -SMTPServer \"XX.XX.XX.XX\" -Template \"c:\script\Welcome mail\Template_FR.html\" -Verbose
} else {
Send-OSCEXWelcomeMail -ScheduledTaskRepeatInterval 240 -From \"CommunicationDOSI@XXXX.fr\" -Subject \"Welcome !\" -SMTPServer \"XX.XX.XX.XX\" -Template \"c:\script\Welcome mail\Template_EN.html\" -Verbose
}
Le problème je pense est le suivant : l'assignation du contenu $newlyCreatedMailboxAlias.DistinguishedName dans la variable $toto.
Pouvez vous m'aider svp ?
Merci d'avance,
Cordialement,
TOR
Message édité par: TOR, à: 22/05/13 11:21<br><br>Message édité par: TOR, à: 27/05/13 16:41
Connexion ou Créer un compte pour participer à la conversation.
- Charly
- Hors Ligne
- Nouveau membre
-
Réduire
Plus d'informations
- Messages : 17
- Remerciements reçus 0
il y a 12 ans 9 mois #14930
par Charly
Réponse de Charly sur le sujet Re:Mail de bienvenue
Bonjour TOR,
C'est assez illisible, tu devrais à minima le placer dans les balises Code, elles servent à ça...
Après ce que tu veux faire ne me parait pas très compliqué, si tu sais sur quel critère te baser pour faire ton test.
Commence déjà par découper ton script en action et trouve les commandes adéquates :
1. Récupérer les utilisateurs récents : Oriente toi vers le module AD de powershell si tu peux, récupère tout les comptes et filtre sur la date de création.
2. Pour chaque utilisateur récupérer leur pays. La ça depend de votre façon de faire, je sais pas comment vous différenciez
3. Envoyer un mail selon les critères demandés.
Une commande base : Send-MailMessage
4. Tu planifies l'execution de ton script une ou deux fois par jour et on en cause plus.
Après j'aime pas être moralisateur, tu n'as peut être pas les droits suffisant pour casser quoi que ce soit, mais par principe on utilise pas sur une infra en production de scripts récupérés sur le net, bon ca vient visiblement 'crosoft donc y a pas grand danger, mais si tu es débutant tu ne maitrise potentiellement pas toutes les incidences de ton script. Ce n'est que mon avis, ça n'engage que moi bien sur
C'est assez illisible, tu devrais à minima le placer dans les balises Code, elles servent à ça...
Après ce que tu veux faire ne me parait pas très compliqué, si tu sais sur quel critère te baser pour faire ton test.
Commence déjà par découper ton script en action et trouve les commandes adéquates :
1. Récupérer les utilisateurs récents : Oriente toi vers le module AD de powershell si tu peux, récupère tout les comptes et filtre sur la date de création.
2. Pour chaque utilisateur récupérer leur pays. La ça depend de votre façon de faire, je sais pas comment vous différenciez
3. Envoyer un mail selon les critères demandés.
Une commande base : Send-MailMessage
4. Tu planifies l'execution de ton script une ou deux fois par jour et on en cause plus.
Après j'aime pas être moralisateur, tu n'as peut être pas les droits suffisant pour casser quoi que ce soit, mais par principe on utilise pas sur une infra en production de scripts récupérés sur le net, bon ca vient visiblement 'crosoft donc y a pas grand danger, mais si tu es débutant tu ne maitrise potentiellement pas toutes les incidences de ton script. Ce n'est que mon avis, ça n'engage que moi bien sur
Connexion ou Créer un compte pour participer à la conversation.
- leroy
- Auteur du sujet
- Hors Ligne
- Nouveau membre
-
Réduire
Plus d'informations
- Messages : 6
- Remerciements reçus 0
il y a 12 ans 9 mois #14942
par leroy
Réponse de leroy sur le sujet Re:Mail de bienvenue
Bonjour Oleg,
Merci de cette réponse.
Je ne poste pas souvent sur les forums, je ne suis donc pas trop habitué aux balises, mais en effet elle aurait été utile
Pour ce qui est des droits, j'ai tous les droits pour faire ces tests, je suis en effet un débutant en powershell, mais j'ai lu cette fonction travailler dessus, et je l'ai comprise. Je vois donc que son exécution ne comporte pas de risque pour notre infrastructure.
Le problème que je rencontre est que le choix du template utilisé par le welcomemail se fait au moment de l'appel de la fonction. Hors les paramètres qui définissent si c'est le template FR ou EN qui doit être envoyé ne sont connu que dans la fonction.
En effet, le test
if ($toto -Match \"OU=FR\"
Vérifie si la varible $newlyCreatedMailboxAlias.DistinguishedName contient FR.
Mon script ne fonctionne pas car le parametre template doit être définie au moment de l'appel de la fonction, et ne peut pas être modifié durant l'exécution de cette fonction.
Comment je peux résoudre ce problème ?
Merci de cette réponse.
Je ne poste pas souvent sur les forums, je ne suis donc pas trop habitué aux balises, mais en effet elle aurait été utile
Pour ce qui est des droits, j'ai tous les droits pour faire ces tests, je suis en effet un débutant en powershell, mais j'ai lu cette fonction travailler dessus, et je l'ai comprise. Je vois donc que son exécution ne comporte pas de risque pour notre infrastructure.
Le problème que je rencontre est que le choix du template utilisé par le welcomemail se fait au moment de l'appel de la fonction. Hors les paramètres qui définissent si c'est le template FR ou EN qui doit être envoyé ne sont connu que dans la fonction.
En effet, le test
if ($toto -Match \"OU=FR\"
Vérifie si la varible $newlyCreatedMailboxAlias.DistinguishedName contient FR.
Mon script ne fonctionne pas car le parametre template doit être définie au moment de l'appel de la fonction, et ne peut pas être modifié durant l'exécution de cette fonction.
Comment je peux résoudre ce problème ?
Connexion ou Créer un compte pour participer à la conversation.
- Laurent Dardenne
- Hors Ligne
- Modérateur
-
Réduire
Plus d'informations
- Messages : 6311
- Remerciements reçus 68
il y a 12 ans 9 mois #14945
par Laurent Dardenne
Tutoriels PowerShell
Réponse de Laurent Dardenne sur le sujet Re:Mail de bienvenue
Salut,
TOR écrit:
Tu es donc libre d'utiliser le bouton Edit et d'autres de ne pas répondre à un message illisible.
La vie est bien faîte
TOR écrit:
Oui, l'usage de balises code à un effet sur les réponses et l'aide que l'on peut obtenir sur ce type de forum.Je ne poste pas souvent sur les forums, je ne suis donc pas trop habitué aux balises, mais en effet elle aurait été utile
Tu es donc libre d'utiliser le bouton Edit et d'autres de ne pas répondre à un message illisible.
La vie est bien faîte
Tutoriels PowerShell
Connexion ou Créer un compte pour participer à la conversation.
- leroy
- Auteur du sujet
- Hors Ligne
- Nouveau membre
-
Réduire
Plus d'informations
- Messages : 6
- Remerciements reçus 0
il y a 12 ans 9 mois #14947
par leroy
Réponse de leroy sur le sujet Re:Mail de bienvenue
Voilà, c'est éditer, et en effet c'est beaucoup plus lisible !
Merci du coup de main.
Merci du coup de main.
Connexion ou Créer un compte pour participer à la conversation.
- Laurent Dardenne
- Hors Ligne
- Modérateur
-
Réduire
Plus d'informations
- Messages : 6311
- Remerciements reçus 68
il y a 12 ans 9 mois #14948
par Laurent Dardenne
Tutoriels PowerShell
Réponse de Laurent Dardenne sur le sujet Re:Mail de bienvenue
TOR écrit:
Mais c'est pas encore ça, car on doit le reformater. La prochaine fois insére ton script en PJ
Alors pour ta modification, de ce que j'ai compris rapido, l'implémentation du paramètre $Template est à revoir.
Effectivement la donnée qui permettra de sélectionner la langue du template est interne à la fonction.
Ensuite le code existant déclenche une exception si le fichier template n'existe pas.
En sachant que tu auras aujourd'hui au moins 2 fichiers template (US et FR) voir plusieurs après-demain, quel comportement souhaites-tu désormais avoir si un des fichiers template n'existe pas ?
Une première idée, modifier le type du paramètre $Template en une hashtable :
[code:1]
[Parameter(Mandatory=$true,Position=7)]
[ValidateNotNullOrEmpty()]
[System.Collections.IDictionary] $Template,
[/code:1]
Ensuite lors de l'appel on lui passe une hashtable de paramètrage :
[code:1]
$Templates=@{
Fr=\"C:\Datas\Template_FR.txt\";
Us=\"C:\Datas\Template_US.txt\"
}
[/code:1]
Un exemple d'appel :
[code:1]
#Send welcome mails to these mailboxes which created four hours before the script is being executed. (In pilot mode)
Send-OSCEXWelcomeMail -ScheduledTaskRepeatInterval 240 -From \"itadmin@corp.contoso.com\" -Subject \"Welcome to Contoso!\" -SMTPServer \"smtpserver.corp.contoso.com\" `
-Template $Templates -RecycleLog -AdminEmailAddress \"itadmin@corp.contoso.com\" -Verbose
[/code:1]
Une \"idée d'ébauche\", syndrome linguistique 'CBP' (Ceinture Bretelle Parachute) du code à modifier :
[code:1]
function GetTemplateFromAlias{
param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
$Alias
)
#Get welcome mail template
if (-not (Test-Path -Path $Template -PathType Leaf)) {
#Cannot find welcome mail template
$errorMsg = $Messages.CannotFindWelcomeMailTemplate
$errorMsg = $errorMsg -f $Template
$customError = New-OSCPSCustomErrorRecord `
-ExceptionString $errorMsg `
-ErrorCategory NotSpecified -ErrorID 1 -TargetObject $pscmdlet
$pscmdlet.ThrowTerminatingError($customError) #TODO ******* QUEL COMPORTEMENT ??
} else {
if ($Alias -Match \"OU=FR\"«»)
{$Key='Fr'}
else
{$Key='Us'}
#TODO ******* Quid des autres langues ?
#Get welcome mail body.
$welcomeMailBody = [string](Get-Content $Template.$Key)
}
#Replace any placeholders with real values
if ($ReplacePlaceholders -ne $null) {
foreach ($placeholders in $ReplacePlaceholders.GetEnumerator())
{
$welcomeMailBody = $welcomeMailBody -replace $($placeholders.Key),$($placeholders.Value)
}
}
} #GetTemplateFromAlias
#Send welcome mail to each newly created mailbox.
if ($newlyCreatedMailboxes -ne $null) {
foreach ($newlyCreatedMailbox in $newlyCreatedMailboxes) {
$newlyCreatedMailboxAlias = $newlyCreatedMailbox.Alias
$welcomeMailBody= GetTemplateFromAlias $newlyCreatedMailboxAlias
$newlyCreatedMailboxDisplayName = $newlyCreatedMailbox.DisplayName
$mailBody = $welcomeMailBody -replace \"Placeholder00\",$newlyCreatedMailboxDisplayName
[/code:1]
Et comme le dit Oleg une refonte ne serait pas de trop, mais ce n'est pas un script évident pour un \"novice\", mais très formateur
Ici le pb n'est pas tellement le code, mais le fonctionnel lié à ton infra.
Yes !et en effet c'est beaucoup plus lisible !
Mais c'est pas encore ça, car on doit le reformater. La prochaine fois insére ton script en PJ
Alors pour ta modification, de ce que j'ai compris rapido, l'implémentation du paramètre $Template est à revoir.
Effectivement la donnée qui permettra de sélectionner la langue du template est interne à la fonction.
Ensuite le code existant déclenche une exception si le fichier template n'existe pas.
En sachant que tu auras aujourd'hui au moins 2 fichiers template (US et FR) voir plusieurs après-demain, quel comportement souhaites-tu désormais avoir si un des fichiers template n'existe pas ?
Une première idée, modifier le type du paramètre $Template en une hashtable :
[code:1]
[Parameter(Mandatory=$true,Position=7)]
[ValidateNotNullOrEmpty()]
[System.Collections.IDictionary] $Template,
[/code:1]
Ensuite lors de l'appel on lui passe une hashtable de paramètrage :
[code:1]
$Templates=@{
Fr=\"C:\Datas\Template_FR.txt\";
Us=\"C:\Datas\Template_US.txt\"
}
[/code:1]
Un exemple d'appel :
[code:1]
#Send welcome mails to these mailboxes which created four hours before the script is being executed. (In pilot mode)
Send-OSCEXWelcomeMail -ScheduledTaskRepeatInterval 240 -From \"itadmin@corp.contoso.com\" -Subject \"Welcome to Contoso!\" -SMTPServer \"smtpserver.corp.contoso.com\" `
-Template $Templates -RecycleLog -AdminEmailAddress \"itadmin@corp.contoso.com\" -Verbose
[/code:1]
Une \"idée d'ébauche\", syndrome linguistique 'CBP' (Ceinture Bretelle Parachute) du code à modifier :
[code:1]
function GetTemplateFromAlias{
param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
$Alias
)
#Get welcome mail template
if (-not (Test-Path -Path $Template -PathType Leaf)) {
#Cannot find welcome mail template
$errorMsg = $Messages.CannotFindWelcomeMailTemplate
$errorMsg = $errorMsg -f $Template
$customError = New-OSCPSCustomErrorRecord `
-ExceptionString $errorMsg `
-ErrorCategory NotSpecified -ErrorID 1 -TargetObject $pscmdlet
$pscmdlet.ThrowTerminatingError($customError) #TODO ******* QUEL COMPORTEMENT ??
} else {
if ($Alias -Match \"OU=FR\"«»)
{$Key='Fr'}
else
{$Key='Us'}
#TODO ******* Quid des autres langues ?
#Get welcome mail body.
$welcomeMailBody = [string](Get-Content $Template.$Key)
}
#Replace any placeholders with real values
if ($ReplacePlaceholders -ne $null) {
foreach ($placeholders in $ReplacePlaceholders.GetEnumerator())
{
$welcomeMailBody = $welcomeMailBody -replace $($placeholders.Key),$($placeholders.Value)
}
}
} #GetTemplateFromAlias
#Send welcome mail to each newly created mailbox.
if ($newlyCreatedMailboxes -ne $null) {
foreach ($newlyCreatedMailbox in $newlyCreatedMailboxes) {
$newlyCreatedMailboxAlias = $newlyCreatedMailbox.Alias
$welcomeMailBody= GetTemplateFromAlias $newlyCreatedMailboxAlias
$newlyCreatedMailboxDisplayName = $newlyCreatedMailbox.DisplayName
$mailBody = $welcomeMailBody -replace \"Placeholder00\",$newlyCreatedMailboxDisplayName
[/code:1]
Et comme le dit Oleg une refonte ne serait pas de trop, mais ce n'est pas un script évident pour un \"novice\", mais très formateur
Ici le pb n'est pas tellement le code, mais le fonctionnel lié à ton infra.
Tutoriels PowerShell
Connexion ou Créer un compte pour participer à la conversation.
Temps de génération de la page : 0.122 secondes
- Vous êtes ici :
-
Accueil
-
forum
-
PowerShell
-
Entraide pour les débutants
- Mail de bienvenue