Public/Enable-DllSearchOrderHardening.ps1

function Enable-DllSearchOrderHardening {
    <#
    .SYNOPSIS
        Mitigates insecure DLL search order behavior described in KB2269637.
    .DESCRIPTION
        Sets the CWDIllegalInDllSearch DWORD value in the Session Manager registry key,
        preventing Windows from searching the current working directory when resolving
        DLL load requests, which removes a common DLL hijacking attack surface.
        A system restart is required for the change to take effect.
    .INPUTS
        None. Parameters must be supplied directly.
    .OUTPUTS
        None.
    .PARAMETER ComputerName
        The target computer. Defaults to the local machine.
    .PARAMETER Force
        Restarts the computer immediately after applying the change.
    .EXAMPLE
        Enable-DllSearchOrderHardening

        Applies the KB2269637 mitigation on the local machine and warns that a restart is needed.
    .EXAMPLE
        Enable-DllSearchOrderHardening -ComputerName 'Server01' -Force

        Applies the mitigation on Server01 and restarts it immediately.
    .NOTES
        Requires Administrator privileges.
        Mitigates the insecure library loading vulnerability described in KB2269637.
        Remote operations require WinRM to be configured on the target machine.
    #>


    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    [OutputType([void])]

    param (
        [Parameter(Mandatory = $false)]
        [string]$ComputerName = $env:COMPUTERNAME,

        [Parameter(Mandatory = $false)]
        [switch]$Force
    )

    $isLocal = ($ComputerName -ieq $env:COMPUTERNAME) -or
               ($ComputerName -ieq 'localhost') -or
               ($ComputerName -eq '127.0.0.1')

    $registryPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager'
    $valueName    = 'CWDIllegalInDllSearch'

    if ($PSCmdlet.ShouldProcess($ComputerName, "Set $valueName = 1 in Session Manager")) {
        if ($isLocal) {
            Set-ItemProperty -Path $registryPath -Name $valueName -Value 1 -Type DWord -ErrorAction Stop
        } else {
            Invoke-Command -ComputerName $ComputerName -ScriptBlock {
                Set-ItemProperty -Path $using:registryPath -Name $using:valueName -Value 1 -Type DWord -ErrorAction Stop
            }
        }

        Write-Verbose "DLL search order hardening applied on '$ComputerName'."
        Write-Warning "A system restart is required for changes to take effect."

        if ($Force -and $PSCmdlet.ShouldProcess($ComputerName, 'Restart computer to apply changes')) {
            Restart-Computer -ComputerName $ComputerName -Force
        }
    }
}