Como desativar o PowerShell 2.0: Guia com roteiro

Olá, profissionais de tecnologia experientes! Se você é um administrador de TI ou trabalha com serviços gerenciados (MSP), sabe que manter seu ambiente seguro é a tarefa número um. Uma área que frequentemente precisa ser examinada é a configuração do PowerShell em seus sistemas Windows. Então, vamos falar sobre o PowerShell 2.0 e por que você pode querer desativá-lo. Melhor ainda, vamos discutir um script que faça o trabalho para você.

Por que desativar o PowerShell 2.0?

Em primeiro lugar, vamos entender por que você deseja desativar o PowerShell 2.0. Essa versão legada do PowerShell não tem muitos dos recursos e aprimoramentos de segurança disponíveis nas versões mais recentes. Isso é praticamente um convite aberto para que agentes mal-intencionados explorem seus sistemas.

O script Disable PowerShell 2.0

Agora que já estabelecemos o “porquê”, vamos falar sobre o “como” O script Disable PowerShell 2.0 é sua solução completa. Escrito no PowerShell 5.1, o script foi projetado para funcionar no Windows 10, Windows Server 2016 e superior.

Veja o que esse script oferece:

Verificação de privilégios elevados

O script executa uma verificação inicial para ver se está sendo executado com privilégios administrativos e, se não estiver, ele o notificará para executá-lo como administrador.

Verificação do sistema operacional e da versão

Antes de tentar remover o PowerShell 2.0, ele verifica sua versão do PowerShell. Você precisa estar executando o PowerShell 5.1 ou posterior. É um bom recurso, que garante que você não estrague a configuração existente.

A remoção

O script emprega comandos diferentes(Disable-WindowsOptionalFeature e Uninstall-WindowsFeature) com base em seu sistema operacional para desativar o PowerShell 2.0. Se o PowerShell 2.0 já estiver desativado, você será informado.

O roteiro

#Requires -Version 5.1

<#
.SYNOPSIS
    Disables PowerShell 2.0.
.DESCRIPTION
    Disables PowerShell 2.0 by removing the feature.
    This script does require that PowerShell 5.1 be installed before hand.
    See: https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/wmf/setup/install-configure
.EXAMPLE
    No parameters needed.
.OUTPUTS
    String[]
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes:
    Initial Release
    (c) 2023 NinjaOne
    By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param ()

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    if ($PSVersionTable.PSVersion -ge [Version]::new(5, 1)) {
        if ($(Get-Command "Disable-WindowsOptionalFeature" -ErrorAction SilentlyContinue).Name -like "Disable-WindowsOptionalFeature") {
            if ($(Get-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2 -ErrorAction SilentlyContinue).State -like "Enabled") {
                # Remove PowerShell 2.0 on Windows 10,11
                try {
                    Disable-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2 -ErrorAction Stop
                    Write-Host "Disabled PowerShell 2.0"
                }
                catch {
                    Write-Error $_
                    Write-Host "Unable to disable PowerShell 2.0"
                    exit 1
                }
            }
            if ($(Get-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2Root -ErrorAction SilentlyContinue).State -like "Enabled") {
                # Remove PowerShell 2.0 on Windows 10, 11, Server 2016
                try {
                    Disable-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2Root -ErrorAction Stop
                    Write-Host "Disabled PowerShell 2.0"
                }
                catch {
                    Write-Error $_
                    Write-Host "Unable to disable PowerShell 2.0"
                    exit 1
                }
            }
            else {
                Write-Host "PowerShell is already disabled."
            }
        }
        if ($(Get-Command "Uninstall-WindowsFeature" -ErrorAction SilentlyContinue).Name -like "Uninstall-WindowsFeature") {
            if ($(Get-WindowsFeature -Name PowerShell-V2) -and $(Get-WindowsFeature -Name PowerShell-V2).InstallState -like "Installed") {
                # Remove PowerShell 2.0 on Windows Server
                try {
                    Uninstall-WindowsFeature -Name PowerShell-V2 -ErrorAction Stop
                    Write-Host "Disabled PowerShell 2.0"
                }
                catch {
                    Write-Error $_
                    Write-Host "Unable to disable PowerShell 2.0"
                    exit 1
                }
            }
            else {
                Write-Host "PowerShell is already disabled."
            }
        }
        if (
            $(Get-Command "Disable-WindowsOptionalFeature" -ErrorAction SilentlyContinue).Name -notlike "Disable-WindowsOptionalFeature" -and 
            $(Get-Command "Uninstall-WindowsFeature" -ErrorAction SilentlyContinue).Name -notlike "Uninstall-WindowsFeature"
        ) {
            Write-Host "Running on an unsupported version of Windows."
            exit 1
        }
    }
    else {
        Write-Host "Please upgrade to 5.1 before disabling PowerShell 2.0."
        exit 1
    }
}
end {}

 

Acesse mais de 300 scripts no NinjaOne Dojo

Obter acesso

Como usar o script

Não é necessário fornecer nenhum parâmetro. Basta executar o script com privilégios administrativos. O script o guiará pelo processo e até mesmo detectará erros para avisá-lo se algo der errado.

Benefícios para profissionais de TI e MSPs

Para os profissionais de TI e MSPs, os benefícios são duplos:

  1. Segurança aprimorada: Ao desativar o PowerShell 2.0, você está fechando um ponto de vulnerabilidade, tornando sua rede mais segura.
  2. Eficiência: Em vez de navegar manualmente até cada servidor e sistema para desativar o PowerShell 2.0, você pode automatizar essa tarefa com este script.

Considerações finais

Desativar o PowerShell 2.0 é fundamental para aprimorar a postura de segurança de seu ambiente Windows. Para os profissionais de TI e MSPs que procuram uma maneira eficiente de fazer isso, nosso script Disable PowerShell 2.0 é uma dádiva de Deus. Ele automatiza a tarefa e vem equipado com verificações para garantir que você esteja fazendo as coisas corretamente.

Próximas etapas

Montar uma equipe de TI eficaz requer uma solução centralizada que seja a principal ferramenta de entrega de serviços. Com NinjaOne, a TI monitora, gerencia, protege e oferece suporte a todos os dispositivos, onde quer que estejam, dispensando infraestrutura complexa no local.

Saiba mais sobre a solução NinjaOne Remote Script Deployment, agende uma demonstração, ou inicie sua avaliação gratuita da plataforma NinjaOne.

Categories:

You might also like