Created
March 5, 2019 16:14
-
-
Save webtroter/f0aac4eab7c7aef1cd34db6d4f7583e3 to your computer and use it in GitHub Desktop.
Rotate-UrgentDL.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#requires -version 5 | |
<# | |
.SYNOPSIS | |
Returns | |
.DESCRIPTION | |
<Brief description of script> | |
.PARAMETER | |
.INPUTS | |
<Inputs if any, otherwise state None> | |
.OUTPUTS Log File | |
The script log file stored in C:\Windows\Temp\<name>.log | |
.NOTES | |
Version: 0.1 | |
Author: Alexis Vézina | |
Company: --------. | |
Creation Date: 2019-03-01 | |
Purpose/Change: Initial script development | |
.EXAMPLE | |
<Example explanation goes here> | |
<Example goes here. Repeat this attribute for more than one example> | |
#> | |
#---------------------------------------------------------[Script Parameters]------------------------------------------------------ | |
[CmdletBinding()] | |
Param ( | |
# Specifies a path to one or more locations. | |
[Parameter(Mandatory=$false, | |
Position=0, | |
ParameterSetName="Log", | |
ValueFromPipeline=$true, | |
ValueFromPipelineByPropertyName=$true, | |
HelpMessage="Path to one locations.")] | |
[Alias("PSPath")] | |
[System.IO.DirectoryInfo] | |
$LogPath = "C:\Services\Logs\", | |
# Switch for testing | |
[Parameter()] | |
[switch] | |
$Test, | |
# Credential | |
[Parameter()] | |
[pscredential] | |
$Credential = $(Get-Credential "[email protected]") | |
) | |
#---------------------------------------------------------[Initialisations]-------------------------------------------------------- | |
#Set Error Action to Silently Continue | |
$ErrorActionPreference = 'SilentlyContinue' | |
$LogName = if ([String]::IsNullOrEmpty($MyInvocation.MyCommand)) { | |
"$($MyInvocation.MyCommand).log" | |
} else { | |
"Rotate.log" | |
} | |
$AvailableTags = @( | |
"Log", | |
"Process", | |
"Meta" | |
) | |
#Import Modules & Snap-ins | |
<# | |
if ($PsCmdlet.ParameterSetName -eq "LogEnabled") { | |
If (!(Get-Module Logging)) { | |
if (!(Get-Module "Logging" -ListAvailable)) { | |
Write-Information -MessageData 'Module is NOT installed, launching installation' -InformationAction Continue | |
Install-Module -Name "Logging" -Scope AllUsers -SkipPublisherCheck -Repository PSGallery | |
} | |
Import-Module Logging | |
} | |
Add-LoggingTarget -Name File -Configuration @{Path = $(Join-Path -Path $LogPath -ChildPath "Check-MSMQ.log")} | |
Write-Log -Message 'Log Enabled!' | |
} | |
if ($PsCmdlet.ParameterSetName -eq "LogEnabled") { | |
Write-Log -Message "Critial is set to {0}, Warning is set to {1}" -Arguments $Critical,$Warning | |
} | |
Write-Verbose -Message $("Critial is set to {0}, Warning is set to {1}" -f $Critical,$Warning) | |
#> | |
#-----------------------------------------------------------[Functions]------------------------------------------------------------ | |
function Update-UrgentDL { | |
<# | |
.SYNOPSIS | |
.DESCRIPTION | |
from https://github.com/mczerniawski/ArcAdminTools/blob/master/ArcAdminTools/Public/Get-FunctionTemplateV5.ps1 | |
.PARAMETER ComputerName | |
.EXAMPLE | |
.INPUTS | |
.OUTPUTS | |
#> | |
[CmdletBinding()] | |
Param( | |
[Parameter(Mandatory = $false)] | |
[string] | |
$DistributionGroup = "[email protected]", | |
# Credential | |
[Parameter()] | |
[pscredential] | |
$Credential, | |
# Switch to test | |
[Parameter(ParameterSetName = "Testing")] | |
[switch] | |
$Test, | |
# Sélection du groupe d'urgence | |
[Parameter()] | |
[ValidateSet("UrgentA", "UrgentB", "UrgentO")] | |
[string] | |
$Groupe | |
) | |
Begin { | |
Write-Information "Starting $($MyInvocation.MyCommand) " -Tags Process | |
Write-Information "Execution Metadata:" -Tags Meta | |
Write-Information "User = $($env:userdomain)\$($env:USERNAME)" -Tags $AvailableTags.Where({$_ -eq "Meta"}) | |
$id = [System.Security.Principal.WindowsIdentity]::GetCurrent() | |
$IsAdmin = [System.Security.Principal.WindowsPrincipal]::new($id).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) | |
Write-Information "Is Admin = $IsAdmin" -Tags Meta | |
Write-Information "Computername = $env:COMPUTERNAME" -Tags Meta | |
Write-Information "Host = $($host.Name)" -Tags Meta | |
Write-Information "PSVersion = $($PSVersionTable.PSVersion)" -Tags Meta | |
Write-Information "Runtime = $(Get-Date)" -Tags Meta | |
Write-Verbose "[$((get-date).TimeOfDay.ToString()) BEGIN ] Starting: $($MyInvocation.Mycommand)" | |
# Connexion à Exchange Online | |
try { | |
$newPSSessionSplat = @{ | |
Credential = $Credential | |
ConnectionUri = 'https://outlook.office365.com/powershell-liveid/' | |
AllowRedirection = $true | |
Authentication = 'Basic' | |
ConfigurationName = 'Microsoft.Exchange' | |
} | |
New-PSSession @newPSSessionSplat -ErrorAction Stop | |
(Get-PSSession).where({$_.ComputerName -eq "outlook.office365.com"}) | New-Variable -Name Session -Scope Script | |
} | |
catch [System.Management.Automation.RuntimeException] { | |
$ErrDetails = [regex]::Matches($PSItem.Exception.ErrorRecord, "\[[^]]*\]").Value.Trim('[',']').Split(',') | ConvertFrom-StringData | |
Write-Information -MessageData $ErrDetails.'FailureCategory' -Tags Log,Process | |
Write-Error $PSItem -ErrorAction Stop | |
} | |
catch { | |
Write-Information -MessageData ('We Caught ' + $_.Exception.GetType().FullName) -Tags Log | |
} | |
if ($Session.State -eq "Opened") { | |
Import-PSSession $Session | |
Write-Information -Tags Log -MessageData "Exchange Online Session Imported" | |
} | |
else { | |
Write-Error -Message "Exchange Online Session not found, exiting" | |
} | |
$UrgentDL = Get-DistributionGroup $DistributionGroup | |
$UrgentA = Get-DistributionGroup "UrgentA" | |
$UrgentB = Get-DistributionGroup "UrgentB" | |
$UrgentO = Get-DistributionGroup "UrgentO" | |
} | |
Process { | |
Write-Information -MessageData "Nous sommes la semaine $(Get-Date -UFormat %V) de l'année $(Get-Date -UFormat %Y)" -Tags Log | |
$UrgentThisWeek = switch ((Get-Date -UFormat %V) % 4) { | |
{$_ -eq 0 -or $_ -eq 1} { | |
$UrgentB | |
} | |
{$_ -eq 2 -or $_ -eq 3} { | |
$UrgentA | |
} | |
Default {} | |
} | |
if ($null -ne $Groupe) { | |
Write-Information -MessageData "Groupe Override" -Tags Log | |
$UrgentThisWeek = Get-DistributionGroup $Groupe | |
} | |
Write-Information -MessageData "C'est le tour de l'équipe $($UrgentThisWeek.Identity)" -Tags Email,Log | |
if ($PsCmdlet.ParameterSetName -eq "Testing") { | |
Write-Information -MessageData "On est en test, on va forcer un groupe, et retirer l'autre." -Tags Log | |
switch ($UrgentThisWeek.Identity) { | |
{$_ -contains $UrgentA.Identity} { | |
Write-Verbose "Urgent A" | |
Add-DistributionGroupMember -Identity $UrgentDL.Identity -Member $_ | |
Remove-DistributionGroupMember -Identity $UrgentDL.Identity -Member $UrgentB.Identity -Confirm:$false | |
} | |
{$_ -contains $UrgentB.Identity} { | |
Write-Verbose "Urgent B" | |
Add-DistributionGroupMember -Identity $UrgentDL.Identity -Member $_ | |
Remove-DistributionGroupMember -Identity $UrgentDL.Identity -Member $UrgentA.Identity -Confirm:$false | |
} | |
Default {} | |
} | |
} | |
else { | |
Update-DistributionGroupMember -Identity $UrgentDL.Identity -Members $UrgentThisWeek.Identity | |
} | |
} | |
End { | |
Write-Verbose "[$((get-date).TimeOfDay.ToString()) END ] Ending: $($MyInvocation.Mycommand)" | |
Write-Information "Ending $($MyInvocation.MyCommand)" -Tags Process | |
} | |
} | |
#-----------------------------------------------------------[Execution]------------------------------------------------------------ | |
Import-Module BetterCredentials | |
Update-UrgentDL -Test:$Test -InformationVariable infoStream -Credential:$Credential | |
Write-Verbose "Ready to write to log" | |
$wantedTags = $AvailableTags.Where({$_ -eq "Log"}) | |
# Join-Path -Path $LogPath -ChildPath $LogName | |
if ($Test) { | |
# [IO.File]::WriteAllLines((Join-Path -Path $LogPath -ChildPath "$LogName.xml"), ($infoStream | ConvertTo-Xml -As String)) | |
$infoStream | Export-Clixml -Path (Join-Path -Path $LogPath -ChildPath "$LogName.xml") -Encoding UTF8 -Force | |
$wantedTags = $AvailableTags | |
} | |
$LogLines = $infoStream.Where({$wantedTags -contains $_.Tags}) | ForEach-Object { "{0},{1},{2},{3},{4}" -f $_.TimeGenerated.ToString('yyyy-MM-dd HH:mm:ss,fff'),$_.MessageData,$_.User,$_.Computer,$_.Tags } | |
# TODO: Fix encoding | |
# Using .NET IO.File instead of Out-File because of encoding. | |
# [IO.File]::WriteAllLines((Join-Path -Path $LogPath -ChildPath $LogName), $LogLines) | |
$LogLines | Out-File -FilePath (Join-Path -Path $LogPath -ChildPath $LogName) -Encoding UTF8 -Force |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment