Added Files

This commit is contained in:
DistractADD
2021-07-06 13:16:46 +10:00
parent f2475a3bdd
commit cfddd4fad2
393 changed files with 65842 additions and 0 deletions

View File

@@ -0,0 +1,420 @@
#requires -Version 2.0
<#
.SYNOPSIS
Exchange Server Logs Cleanup
.DESCRIPTION
Cleanup some Exchange Server logs.
.EXAMPLE
PS C:\> .\CleanupExchangeLogs.ps1
.NOTES
Releasenotes:
1.0.1 2019-07-08: Move the delete process to the dedicated Invoke-CleanupOldFiles function
1.0.0 2019-02-04: Internal Release
THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
.LINK
Invoke-CleanupOldFiles
#>
[CmdletBinding(ConfirmImpact = 'Low')]
param ()
begin
{
# You can change the number of days here
$days = 30
#region PowerShell2WorkArounds
<#
The following stuff is a workaround to make everything compatible to PowerShell 2.0
Old, but some still have the old crap on the Exchange server running, sorry!
#>
#region RequiredModuleWorkAround
if (Get-Module -Name webadministration -ListAvailable -ErrorAction SilentlyContinue)
{
try
{
$null = (Import-Module -Name webadministration -Force -ErrorAction Stop)
}
catch
{
#region ErrorHandler
# get error record
[Management.Automation.ErrorRecord]$e = $_
# retrieve information about runtime error
$info = @{
Exception = $e.Exception.Message
Reason = $e.CategoryInfo.Reason
Target = $e.CategoryInfo.TargetName
Script = $e.InvocationInfo.ScriptName
Line = $e.InvocationInfo.ScriptLineNumber
Column = $e.InvocationInfo.OffsetInLine
}
$info | Out-String | Write-Verbose
Write-Error -Message ($info.Exception) -ErrorAction Stop
# Only here to catch a global ErrorAction overwrite
break
#endregion ErrorHandler
}
}
else
{
#region ErrorHandler
$paramWriteError = @{
Message = 'The required Module (webadministration) is missing!'
Category = 'ObjectNotFound'
ErrorAction = 'Stop'
}
Write-Error @paramWriteError
# Only here to catch a global ErrorAction overwrite
break
#endregion ErrorHandler
}
#endregion RequiredModuleWorkAround
#region RunAsAdministrator
function Test-Administrator
{
<#
.SYNOPSIS
Check if this is an elevated shell
.DESCRIPTION
Check if this is an elevated shell.
In Powershell 4.0 it can be replaced with:
#Requires -RunAsAdministrator
.EXAMPLE
PS C:\> Test-Administrator
.NOTES
In Powershell 4.0 it can be replaced with: Requires -RunAsAdministrator
License: Public Domain
#>
[CmdletBinding(ConfirmImpact = 'None')]
[OutputType([bool])]
param ()
process
{
$user = [Security.Principal.WindowsIdentity]::GetCurrent()
(New-Object -TypeName Security.Principal.WindowsPrincipal -ArgumentList $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
}
if ((Test-Administrator) -ne $true)
{
#region ErrorHandler
Write-Error -Message 'The current Windows PowerShell session is not running as Administrator. Start Windows PowerShell by using the Run as Administrator option, and then try running the script again.' -Category NotEnabled -ErrorAction Stop
# Only here to catch a global ErrorAction overwrite
break
#endregion ErrorHandler
}
#endregion RunAsAdministrator
#endregion PowerShell2WorkArounds
# Cleanup
$LogDirList = $null
# Create a new List
$LogDirList = (New-Object -TypeName System.Collections.Generic.List[System.Object])
# Add static Directories to the new list
if ($env:ExchangeInstallPath)
{
$LogDirList.Add($env:ExchangeInstallPath + 'Logging\')
# Another possible Directory
#$LogDirList.Add($env:ExchangeInstallPath + 'Bin\Search\Ceres\Diagnostics\Logs\')
}
else
{
Write-Warning -Message 'This is not a Exchange Server!'
}
# Get a list of all IIS Websites and add to the new list
$AllIISSites = (Get-Website)
if ($AllIISSites)
{
# Loop over the IIS Site list
foreach ($SingleWebSite in $AllIISSites)
{
# Cleanup
$IISLogDirectory = $null
# Get the Log-Directory from the IIS Info
$IISLogDirectory = ($SingleWebSite.logfile.directory)
<#
Replace the returned %SystemDrive% with your system drive.
This is your BOOT Drive!!! Usually it is C:
#>
if ($IISLogDirectory -match '%SystemDrive%')
{
Write-Verbose -Message 'Mangle the SystemDrive within the variable...'
$IISLogDirectory = ($IISLogDirectory -replace '%SystemDrive%', 'C:')
}
# Add the log Directory to the List
$LogDirList.Add($IISLogDirectory)
}
}
else
{
Write-Warning -Message 'No IIS Log-Directory found!'
}
# Make all entries in the List unique
$LogDirList = ($LogDirList | Sort-Object | Get-Unique)
#region Invoke-CleanupOldFiles
function Invoke-CleanupOldFiles
{
<#
.SYNOPSIS
Remove files older then a given number of days
.DESCRIPTION
Remove files older then a given number of days.
Mostly used within cleanup Tasks.
.PARAMETER Path
Path to search.
.PARAMETER Age
Age of files to remove, in days.
Defaults to 30
.EXAMPLE
PS C:\> Invoke-CleanupoldFiles -Path 'C:\inetpub\logs\LogFiles'
.EXAMPLE
PS C:\> Invoke-CleanupoldFiles -Path 'C:\inetpub\logs\LogFiles' -Age 14
.NOTES
Releasenotes:
1.0.1 2019-07-08: Rework and splatting
1.0.0 2019-02-04: Internal Release
THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
.LINK
Get-ChildItem
.LINK
Test-Path
.LINK
Get-Date
#>
[CmdletBinding(ConfirmImpact = 'Low')]
param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
Position = 0,
HelpMessage = 'Path to search.')]
[ValidateNotNullOrEmpty()]
[Alias('TargetFolder')]
[string]
$Path,
[Parameter(ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
Position = 1)]
[ValidateNotNullOrEmpty()]
[Alias('Days')]
[int]
$Age = 30
)
process
{
if (Test-Path -Path $Path)
{
# Save the date to use it for the compare
$Now = (Get-Date)
# Today minus given days
$LastWrite = $Now.AddDays(-$days)
# Splatting the parameters
$paramGetChildItem = @{
Path = $Path
Include = '*.log', '*.blg'
Recurse = $true
}
# Find all Files to Delete (e.g. older then the given value)
$Files = (Get-ChildItem @paramGetChildItem | Where-Object -FilterScript {
(-not ($_.PSIsContainer)) -and ($_.LastWriteTime -le $LastWrite)
} | Select-Object -ExpandProperty fullname)
# Loop over the list of Files
foreach ($File in $Files)
{
# Support for WhatIf and Verbose
if ($pscmdlet.ShouldProcess($File, 'Remove'))
{
# Splatting the parameters
$paramRemoveItem = @{
Path = $File
ErrorAction = 'SilentlyContinue'
Force = $true
WhatIf = $false
}
# Remove the files that we found
$null = (Remove-Item @paramRemoveItem)
}
}
}
else
{
#region ErrorHandler
# get error record
[Management.Automation.ErrorRecord]$e = $_
# retrieve information about runtime error
$info = @{
Exception = $e.Exception.Message
Reason = $e.CategoryInfo.Reason
Target = $e.CategoryInfo.TargetName
Script = $e.InvocationInfo.ScriptName
Line = $e.InvocationInfo.ScriptLineNumber
Column = $e.InvocationInfo.OffsetInLine
}
$info | Out-String | Write-Verbose
Write-Error -Message ($info.Exception) -ErrorAction Stop
# Only here to catch a global ErrorAction overwrite
break
#endregion ErrorHandler
}
}
}
#endregion Invoke-CleanupOldFiles
}
process
{
# Do we have a lif of directories?
if ($LogDirList)
{
# Loop over the List of Directories
foreach ($LogDir in $LogDirList)
{
Write-Verbose -Message "Removing logs from $LogDir older then $days days"
try
{
# Do we have a DAY value
if ($days)
{
# Splatting the parameters
$paramInvokeCleanupoldFiles = @{
Path = $LogDir
Age = $days
ErrorAction = 'Stop'
verbose = $true
}
}
else
{
# Splatting the parameters
$paramInvokeCleanupoldFiles = @{
Path = $LogDir
ErrorAction = 'Stop'
verbose = $true
}
}
# Invoke the internal Fun
Invoke-CleanupOldFiles @paramInvokeCleanupoldFiles
}
catch
{
#region ErrorHandler
# get error record
[Management.Automation.ErrorRecord]$e = $_
# retrieve information about runtime error
$info = @{
Exception = $e.Exception.Message
Reason = $e.CategoryInfo.Reason
Target = $e.CategoryInfo.TargetName
Script = $e.InvocationInfo.ScriptName
Line = $e.InvocationInfo.ScriptLineNumber
Column = $e.InvocationInfo.OffsetInLine
}
$info | Out-String | Write-Verbose
Write-Error -Message ($info.Exception) -ErrorAction Stop
# Only here to catch a global ErrorAction overwrite
break
#endregion ErrorHandler
}
}
}
else
{
#region ErrorHandler
$paramWriteError = @{
Message = 'No directories found to cleanup'
Category = 'ObjectNotFound'
ErrorAction = 'Stop'
}
Write-Error @paramWriteError
# Only here to catch a global ErrorAction overwrite
break
#endregion ErrorHandler
}
}
#region LICENSE
<#
BSD 3-Clause License
Copyright (c) 2021, enabling Technology
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#>
#endregion LICENSE
#region DISCLAIMER
<#
DISCLAIMER:
- Use at your own risk, etc.
- This is open-source software, if you find an issue try to fix it yourself. There is no support and/or warranty in any kind
- This is a third-party Software
- The developer of this Software is NOT sponsored by or affiliated with Microsoft Corp (MSFT) or any of its subsidiaries in any way
- The Software is not supported by Microsoft Corp (MSFT)
- By using the Software, you agree to the License, Terms, and any Conditions declared and described above
- If you disagree with any of the terms, and any conditions declared: Just delete it and build your own solution
#>
#endregion DISCLAIMER

View File

@@ -0,0 +1,219 @@
#requires -Version 3.0 -RunAsAdministrator
<#
.SYNOPSIS
Cleanup some of the Exchange Logs
.DESCRIPTION
Cleanup some of the Exchange Logs
.EXAMPLE
PS C:\> .\Clear-LogFileDirectory.ps1
.NOTES
Wrapper for the Clear-LogFileDirectory function
Everything is hardcoded for this wrapper ;-)
.LINK
Clear-LogFileDirectory
#>
[CmdletBinding(ConfirmImpact = 'None')]
param ()
# Files older then 1 day are deleted
$Days = 1
# Exchange Base Directory
$ExchangeBaseDir = 'D:\Exchange Server'
# Exchange Version (Directory)
$ExchangeVersion = 'V15'
# Where to find the IIS stuff
$IISBaseDir = "$env:HOMEDRIVE\inetpub"
#region IIS
# Append the Log Stuff for the Call below
$IISLogPath = $IISBaseDir + '\logs\LogFiles\'
#endregion IIS
#region Exchange
# Combine the values
$ExchangeDirectoryPath = $ExchangeBaseDir + '\' + $ExchangeVersion
# Append the Log Stuff for the Call below
$ExchangeLoggingPath = $ExchangeDirectoryPath + '\Logging\'
$ExchangeETLTraces = $ExchangeDirectoryPath + '\Bin\Search\Ceres\Diagnostics\ETLTraces\'
$ExchangeETLLogs = $ExchangeDirectoryPath + '\Bin\Search\Ceres\Diagnostics\Logs'
#endregion Exchange
#region HelperFunction
function Clear-LogFileDirectory
{
<#
.SYNOPSIS
Cleanup Files in a given Directory
.DESCRIPTION
Cleanup Files in a given Directory
.PARAMETER Path
Specifies a path, multi-value or wildcards are not yet supported!
No default so far!
.PARAMETER Days
Age of the Files to Delete.
Default is 7
.EXAMPLE
PS C:\> Clear-LogFileDirectory -Path "c:\inetpub\logs\LogFiles\"
.NOTES
Mind the Gap:
Everything within the given directory will be deleted, without any further interaction!
#>
[CmdletBinding(ConfirmImpact = 'Low',
SupportsShouldProcess)]
param
(
[Parameter(Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName,
HelpMessage = 'Specifies a path, multivalue or wildcards are not yet supported!')]
[ValidateNotNullOrEmpty()]
[Alias('Folder', 'TargetFolder')]
[string]
$Path,
[Parameter(ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[Alias('Age', 'FileAge')]
[int]
$Days = 7
)
begin
{
#region Defaults
$CNT = 'Continue'
$SCT = 'SilentlyContinue'
#endregion Defaults
Write-Verbose -Message ('START: Processing of {0}' -f $Path)
}
process
{
if (Test-Path -Path $Path -ErrorAction $SCT)
{
$Now = (Get-Date)
$LastWrite = $Now.AddDays(-$Days)
#region FindAndFilterFiles
# Splat the Parameters
$paramFindAndFilterFiles = @{
Path = $Path
Recurse = $true
ErrorAction = $SCT
}
$Files = (Get-ChildItem @paramFindAndFilterFiles | Where-Object -FilterScript {
($_.Name -like '*.log') -or ($_.Name -like '*.blg') -or ($_.Name -like '*.etl')
} | Where-Object -FilterScript {
$_.lastWriteTime -le $LastWrite
} | Select-Object -ExpandProperty FullName)
#endregion FindAndFilterFiles
#region FileLooper
foreach ($File in $Files)
{
Write-Verbose -Message ('Deleting file {0}' -f $File)
try
{
if ($pscmdlet.ShouldProcess($File, 'Delete'))
{
#region DeleteFilesFound
# Splat the Parameters
$paramDeleteFilesFound = @{
Path = $File
Force = $true
Confirm = $false
ErrorAction = 'Stop'
}
$null = (Remove-Item @paramDeleteFilesFound)
#endregion DeleteFilesFound
}
}
catch
{
#region ErrorHandler
# get error record
[Management.Automation.ErrorRecord]$e = $_
# retrieve information about runtime error
$info = [PSCustomObject]@{
Exception = $e.Exception.Message
Reason = $e.CategoryInfo.Reason
Target = $e.CategoryInfo.TargetName
Script = $e.InvocationInfo.ScriptName
Line = $e.InvocationInfo.ScriptLineNumber
Column = $e.InvocationInfo.OffsetInLine
}
$info | Out-String | Write-Verbose
Write-Warning -Message ($info.Exception) -ErrorAction $CNT -WarningAction $CNT
#endregion ErrorHandler
}
}
#endregion FileLooper
}
else
{
Write-Error -Message ("The folder {0} doesn't exist! Check the folder path!" -f $Path)
}
}
end
{
Write-Verbose -Message ('DONE: Processed {0}' -f $Path)
}
}
#endregion HelperFunction
#region FunctionWrapper
Clear-LogFileDirectory -Path $IISLogPath -Days $Days
Clear-LogFileDirectory -Path $ExchangeLoggingPath -Days $Days
Clear-LogFileDirectory -Path $ExchangeETLTraces -Days $Days
Clear-LogFileDirectory -Path $ExchangeETLLogs -Days $Days
#endregion FunctionWrapper
#region LICENSE
<#
BSD 3-Clause License
Copyright (c) 2021, enabling Technology
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#>
#endregion LICENSE
#region DISCLAIMER
<#
DISCLAIMER:
- Use at your own risk, etc.
- This is open-source software, if you find an issue try to fix it yourself. There is no support and/or warranty in any kind
- This is a third-party Software
- The developer of this Software is NOT sponsored by or affiliated with Microsoft Corp (MSFT) or any of its subsidiaries in any way
- The Software is not supported by Microsoft Corp (MSFT)
- By using the Software, you agree to the License, Terms, and any Conditions declared and described above
- If you disagree with any of the terms, and any conditions declared: Just delete it and build your own solution
#>
#endregion DISCLAIMER

View File

@@ -0,0 +1,91 @@
#requires -Version 2.0
<#
.SYNOPSIS
Enabling Modern Authentication for Exchange Online
.DESCRIPTION
Enabling Modern Authentication for Exchange Online (Office 365)
.EXAMPLE
PS C:\> .\Enable-ModernAuth-Exchange.ps1
.NOTES
Works fine with Office 2013 and Office 2016 on Windows. Tested with Office 2016 on the Mac.
You must enable it on your computers (Windows and Mac) as well! It is disabled by default.
.LINK
https://blogs.technet.microsoft.com/canitpro/2015/09/11/step-by-step-setting-up-ad-fs-and-enabling-single-sign-on-to-office-365/
#>
[CmdletBinding()]
param ()
begin
{
# The Exchange Online URL
$ExoURL = 'https://outlook.office365.com/powershell-liveid/'
# Same as above, but for the German Office 365 (MCD)
#$ExoURL = 'https://outlook.office.de/powershell-liveid/'
# The Exchange Online Authentication method
$ExoAuth = 'Basic'
}
process
{
# Get the Credentials (Could also be imported if you have dem saved)
$credentials = (Get-Credential)
# Create the new session
$paramNewPSSession = @{
ConfigurationName = 'Microsoft.Exchange'
ConnectionUri = $ExoURL
Credential = $credentials
Authentication = $ExoAuth
AllowRedirection = $true
}
$ExoSession = (New-PSSession @paramNewPSSession)
# Start the Session by importing it to the PowerShell Session
$null = (Import-PSSession -Session $ExoSession)
# Enable Modern Authentication, use $false to disable it
$null = (Set-OrganizationConfig -OAuth2ClientProfileEnabled $true)
}
end
{
# Cleanup
$ExoSession = $null
}
#region LICENSE
<#
BSD 3-Clause License
Copyright (c) 2021, enabling Technology
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#>
#endregion LICENSE
#region DISCLAIMER
<#
DISCLAIMER:
- Use at your own risk, etc.
- This is open-source software, if you find an issue try to fix it yourself. There is no support and/or warranty in any kind
- This is a third-party Software
- The developer of this Software is NOT sponsored by or affiliated with Microsoft Corp (MSFT) or any of its subsidiaries in any way
- The Software is not supported by Microsoft Corp (MSFT)
- By using the Software, you agree to the License, Terms, and any Conditions declared and described above
- If you disagree with any of the terms, and any conditions declared: Just delete it and build your own solution
#>
#endregion DISCLAIMER

View File

@@ -0,0 +1,226 @@
function Get-ADExchangeServers
{
<#
.SYNOPSIS
Get all Exchange Servers from Active Directory
.DESCRIPTION
This function gets a list with info of all Exchange Servers from the Active Directory.
The Exchange tools (or a PowerShell Connection) is not needed.
That is the major difference to Get-ExchangeServer
.EXAMPLE
# Get all Exchange Servers from Active Directory
PS> Get-ADExchangeServers
path : http://nycexch01.contoso.com/powershell
server : NYCEXCH01
Fullver : Version 15.1 (Build 31034.26)
version : 15.1
Site : HQ
path : http://nycexch02.contoso.com/powershell
server : NYCEXCH02
Fullver : Version 15.1 (Build 31034.26)
version : 15.1
Site : HQ
.EXAMPLE
# No Exchange Server found! (Error)
PS> Get-ADExchangeServers
Get-ADExchangeServers : Unable to get the Exchange Information from the Active Directory!
.NOTES
Only Exchange Servers with a configured PowerShell URI will be dumped
#>
[CmdletBinding()]
[OutputType([psobject])]
param ()
begin
{
# Define some defaults
$ErrorMessage = 'Unable to get the Exchange Information from the Active Directory!'
$SC = 'SilentlyContinue'
$STP = 'Stop'
# Search configuration partition for Exchange Servers where the powershell virtual directory is enabled
try
{
$ActiveDirectoryInfo = (New-Object -TypeName adsisearcher -ArgumentList ([adsi]"LDAP://$(([adsi]'LDAP://rootdse').configurationNamingContext)"), '(&(objectclass=msExchPowerShellVirtualDirectory)(msexchinternalhostname=*))')
}
catch
{
$paramWriteError = @{
Message = $ErrorMessage
ErrorAction = $STP
WarningAction = $SC
}
Write-Error @paramWriteError
break
}
if (-not ($ActiveDirectoryInfo))
{
$paramWriteError = @{
Message = $ErrorMessage
ErrorAction = $STP
WarningAction = $SC
}
Write-Error @paramWriteError
break
}
# Create a new Object
$ADExchangeInfo = @()
}
process
{
try
{
$ActiveDirectoryInfo.findall() | Sort-Object -Descending -Property {
$_.properties.msexchversion[0]
} | ForEach-Object -Process {
# Define some defauts
$NONE = ' '
$COM = ','
if ($_.properties.msexchinternalhostname[0])
{
if ($_.properties.distinguishedname[0])
{
$SrvLdapPath = ($_.properties.distinguishedname[0] -split $COM)[3 .. 100] -join $COM
try
{
$SingleServerObject = [adsi]"LDAP://$SrvLdapPath"
}
catch
{
$SingleServerObject = $null
}
if ($SingleServerObject)
{
if ($SingleServerObject.serialnumber[0])
{
$SingleFullVersion = $SingleServerObject.serialnumber[0]
}
else
{
$SingleFullVersion = $null
}
if (($SingleServerObject.serialNumber -split $NONE)[1])
{
$SingleShortVersion = ($SingleServerObject.serialNumber -split $NONE)[1]
}
else
{
$SingleShortVersion = $null
}
if ($SingleServerObject.name[0])
{
$SingleServer = $SingleServerObject.name[0]
}
else
{
$SingleServer = $null
}
if ($SingleServerObject.msExchServerSite[0])
{
$SingleActiveDirectorySite = $SingleServerObject.msExchServerSite[0] -replace '^CN=|,.*$', ''
}
else
{
$SingleActiveDirectorySite = $null
}
}
if ($_.properties.msexchinternalhostname[0])
{
# With each virtual directory create an object to represent its details,
# if List Version or site is included, also find the server object
$paramNewObject = @{
TypeName = 'psobject'
Property = @{
path = $_.properties.msexchinternalhostname[0]
server = $SingleServer
Site = $SingleActiveDirectorySite
version = $SingleShortVersion
Fullver = $SingleFullVersion
}
}
$SingleExchangeInfo = (New-Object @paramNewObject)
# Append the Info to the Object
$ADExchangeInfo += $SingleExchangeInfo
}
}
}
}
}
catch
{
# Do nothing
Write-Verbose -Message 'Something went wrong...'
}
}
end
{
# Just dump the plain object
if ($ADExchangeInfo)
{
$ADExchangeInfo
}
else
{
$paramWriteError = @{
Message = $ErrorMessage
ErrorAction = $STP
WarningAction = $SC
}
Write-Error @paramWriteError
break
}
}
}
#region LICENSE
<#
BSD 3-Clause License
Copyright (c) 2021, enabling Technology
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#>
#endregion LICENSE
#region DISCLAIMER
<#
DISCLAIMER:
- Use at your own risk, etc.
- This is open-source software, if you find an issue try to fix it yourself. There is no support and/or warranty in any kind
- This is a third-party Software
- The developer of this Software is NOT sponsored by or affiliated with Microsoft Corp (MSFT) or any of its subsidiaries in any way
- The Software is not supported by Microsoft Corp (MSFT)
- By using the Software, you agree to the License, Terms, and any Conditions declared and described above
- If you disagree with any of the terms, and any conditions declared: Just delete it and build your own solution
#>
#endregion DISCLAIMER

View File

@@ -0,0 +1,91 @@
<#
.SYNOPSIS
Helper script to investigate a Hafnium attack
.DESCRIPTION
Helper script to investigate a Hafnium attack
.PARAMETER ReportPath
Where to save the reports
.EXAMPLE
PS C:\> .\Get-HafniumReports.ps1
.LINK
https://discuss.elastic.co/t/detection-and-response-for-hafnium-activity/266289
. LINK
https://www.msxfaq.de/exchange/update/hafnium-nachbereitung.htm
.NOTES
This does NOT replace a Anti Virus scanner and also does NOT replace the Microsoft investigation scripts!
You can use this to bring your ongoing security investigation(s) a step forward, not more but not less.
#>
[CmdletBinding(ConfirmImpact = 'None')]
param
(
[Parameter(ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[ValidateNotNull()]
[Alias('Path')]
[string]
$ReportPath = 'C:\scripts\PowerShell\reports\Hafnium\'
)
begin
{
# Create the report directory, if needed
if (-not (Test-Path -Path $ReportPath -ErrorAction SilentlyContinue))
{
$null = (New-Item -Path $ReportPath -ItemType Directory -Force -ErrorAction Stop)
}
# Create a Timestamp
$TimeStamp = (Get-Date -Format 'yyyyMMdd_HHmmss')
}
process
{
<#
Look for commands like "Set-OABVirtualDirectory" - This is one of the known commands that the attackers used.
#>
# Get Exchange Event Logs
$null = (Get-WinEvent -LogName 'MSExchange Management' -ErrorAction SilentlyContinue | Export-Csv -Path ($ReportPath + 'MSExchangeManagement_' + $TimeStamp + '.csv') -NoTypeInformation -Force -Encoding UTF8 -ErrorAction SilentlyContinue)
<#
Look for tasks that you don't know.
"WwanSvcdcs" is one of the names that are known as related to Hafnium
Please keep in mind: Windows itself use Scheduled Tasks a lot!
#>
# Get Scheduled Task info
$null = (Get-ScheduledTask -ErrorAction SilentlyContinue | Select-Object -Property actions -ExpandProperty actions -ErrorAction SilentlyContinue | Export-Csv -Path ($ReportPath + 'ScheduledTaskInfo_' + $TimeStamp + '.csv') -NoTypeInformation -Force -Encoding UTF8 -ErrorAction SilentlyContinue)
<#
See above, and watch for tasks that are created since January 2021 that you can not identify.
Please keep in mind: Windows itself use Scheduled Tasks a lot!
#>
# TaskScheduler info
$null = (Get-WinEvent -LogName 'Microsoft-Windows-TaskScheduler/Operational' -ErrorAction SilentlyContinue | Export-Csv -Path ($ReportPath + 'TaskScheduler_' + $TimeStamp + '.csv') -NoTypeInformation -Force -Encoding UTF8 -ErrorAction SilentlyContinue)
<#
PowerShell keeps a history that will be saved into a plain ASC File. At least if the ReadLine Module is installed!
A bit work, but you can at least try to identify something strange here!
#>
# Get all History Files from PowerShell
$null = (Get-ChildItem -Path 'C:\Users' -Filter 'ConsoleHost_history.txt' -Recurse -ErrorAction SilentlyContinue -Force | ForEach-Object -Process {
$null = (Get-Content -Path $_.FullName -ErrorAction SilentlyContinue | Out-File -FilePath ($ReportPath + 'PowerShell_History_' + $TimeStamp + '.txt') -Encoding utf8 -Append -ErrorAction SilentlyContinue)
})
}
end
{
# Open the directory in the File Explorer
Invoke-Item -Path $ReportPath
}

View File

@@ -0,0 +1,29 @@
BSD 3-Clause License
Copyright (c) 2021, enabling Technology <http://enatec.io>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,8 @@
# Legacy Notice
I no longer run Exchange, Skype for Business, or any other Office Server on Premises.
This is my personal [reaction](https://hochwald.net/microsoft-rolls-back-decision-to-take-away-internal-usage-rights-from-partners/) to the changes that Microsoft [announced](https://hochwald.net/microsoft-is-going-to-kill-internal-use-rights-benefit-for-partners/) for the Internal Use Rights (IUR) program. I know that they decided to reverse that changes and in theory, I could still legally use the software. However, I decided to decommission everything licensed under the terms of the Internal Use Rights (IUR) program.
In my opinion, the community always should have some benefits from the Internal Use Rights (IUR) program and/or Action Pack. Now that I decided to drop out, there will be no more such benefits.
I will _no longer maintain_ the scripts related to the Microsoft Office (on Premises) servers. They will remain here, but unmaintained. Fork the repository and maintain or extend them if you like to. The [License](https://github.com/jhochwald/PowerShell-collection/blob/master/LICENSE) allows that easily.

View File

@@ -0,0 +1,109 @@
#requires -Version 1.0
<#
.SYNOPSIS
Uninstalls the old and retired Anti-spam Agents from an Exchange Server
.DESCRIPTION
Microsoft announced that they deprecated the support for the SmartScreen Anti-spam content filters for Exchange Servers. This script uninstalls the old an retired SmartScreen Anti-spam Agents from the local Exchange Server.
This is an easy to use and light weight replacement for Uninstall-AntiSpamAgents.ps1 from the \Scripts of your Exchange Installation, it will remove just the dead parts and leave the rest as it is. Some find that it might be better to leave the rest intact.
.EXAMPLE
PS C:\> Remove-AntiSpamAgents
.NOTES
Find a suitable an solid replacement solution for your email hygiene. This could be any 3rd party solution on premise or cloud. Never use email without any good email hygiene!
If you want, you might run the Uninstall-AntiSpamAgents.ps1 from the \Scripts folder created by Setup during Exchange installation. It removes everything related to the AntiSpamAgents.
Taken from the links below.
.LINK
https://blogs.technet.microsoft.com/exchange/2016/09/01/deprecating-support-for-smartscreen-in-outlook-and-exchange/
.LINK
https://blogs.technet.microsoft.com/exchange/2017/03/23/exchange-server-edge-support-on-windows-server-2016-update/
#>
[CmdletBinding(ConfirmImpact = 'Medium',
SupportsShouldProcess = $true)]
param ()
begin
{
# Constants
$STP = 'SilentlyContinue'
# Agents to remove
$TransportAgentsToRemove = 'Content Filter Agent', 'Sender Id Agent', 'Protocol Analysis Agent'
}
process
{
# Loop over the List
foreach ($TransportAgentToRemove in $TransportAgentsToRemove)
{
# Do we have the agent we would like to remove?
if (Get-TransportAgent -Identity $TransportAgentToRemove -ErrorAction $STP -WarningAction $STP)
{
Write-Verbose -Message "Try to remove $TransportAgentToRemove"
try
{
# Do it, or dry run it?
if ($pscmdlet.ShouldProcess("$TransportAgentToRemove", 'Remove TransportAgent'))
{
# Remove it...
$paramUninstallTransportAgent = @{
Identity = $TransportAgentToRemove
ErrorAction = $STP
WarningAction = $STP
Confirm = $false
}
$null = (Uninstall-TransportAgent @paramUninstallTransportAgent)
}
}
catch
{
# Whoopsss
Write-Warning -Message "Unable to remove $TransportAgentToRemove"
}
Write-Verbose -Message "$TransportAgentToRemove was removed"
}
else
{
Write-Verbose -Message "Sorry, $TransportAgentToRemove was not found..."
}
}
}
#region LICENSE
<#
BSD 3-Clause License
Copyright (c) 2021, enabling Technology
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#>
#endregion LICENSE
#region DISCLAIMER
<#
DISCLAIMER:
- Use at your own risk, etc.
- This is open-source software, if you find an issue try to fix it yourself. There is no support and/or warranty in any kind
- This is a third-party Software
- The developer of this Software is NOT sponsored by or affiliated with Microsoft Corp (MSFT) or any of its subsidiaries in any way
- The Software is not supported by Microsoft Corp (MSFT)
- By using the Software, you agree to the License, Terms, and any Conditions declared and described above
- If you disagree with any of the terms, and any conditions declared: Just delete it and build your own solution
#>
#endregion DISCLAIMER