Ver demo×
×

¡Vean a NinjaOne en acción!

Cómo desactivar PowerShell 2.0: guía con el script

desactivar powershell 2

¡Hola, profesional de la tecnología! Si eres administrador de TI o trabajas en el sector de los servicios gestionados (MSP), sabrás que mantener la seguridad de tu entorno es tu máxima prioridad. Un área que a menudo necesita ser examinada es la configuración de PowerShell en los sistemas Windows. Hablemos, pues, de PowerShell 2.0 y de por qué conviene desactivarlo. O, mejor aún, hablemos de script que lo haga por ti.

¿Por qué desactivar PowerShell 2.0?

En primer lugar, vamos a tratar de entender por qué querrías desactivar PowerShell 2.0. Esta versión heredada de PowerShell no cuenta con muchas de las funciones y mejoras de seguridad disponibles en las versiones más recientes. Es prácticamente una invitación abierta a los actores malintencionados para que exploten tus sistemas.

El script para desactivar PowerShell 2.0

Ahora que hemos establecido el «por qué», hablemos del «cómo». El script Disable PowerShell 2.0 es una solución integral. Escrito en PowerShell 5.1, el script está diseñado para funcionar en Windows 10, Windows Server 2016 y superiores.

Esto es lo que ofrece este script:

Control de privilegios elevados

El script realiza una comprobación inicial para ver si se está ejecutando con privilegios de administrador y, si no es así, te avisará para que lo ejecutes como administrador.

Comprobación del sistema operativo y la versión

Antes de intentar eliminar PowerShell 2.0, comprueba tu versión de PowerShell. Tienes que ejecutar PowerShell 5.1 o posteriores. Es una función útil, que te evita crear problemas en tu configuración actual.

La eliminación

El script emplea diferentes comandos(Disable-WindowsOptionalFeaturey Uninstall-WindowsFeature) en función de cuál sea tu sistema operativo para desactivar PowerShell 2.0. Si PowerShell 2.0 ya está desactivado, te lo hará saber.

El script

#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 {}

 

Accede a más de 300 scripts en el Dojo de NinjaOne

Obtén acceso

Cómo utilizar el script

No necesitas proporcionar ningún parámetro; basta con ejecutar el script con privilegios administrativos. El script te guiará a través del proceso e incluso detectará errores para avisarte si algo va mal.

Ventajas para los profesionales de TI y los MSP

Para los profesionales de TI y los MSP, las ventajas son dobles:

  1. Seguridad reforzada: al desactivar PowerShell 2.0, estás cerrando un punto vulnerable, con lo que tu red será más segura.
  2. Eficacia: En lugar de ir manualmente a cada servidor y sistema para desactivar PowerShell 2.0, puedes automatizar esta tarea con este script.

Reflexiones finales

Desactivar PowerShell 2.0 es crucial para mejorar la seguridad de tu entorno Windows. Para los profesionales de TI y los MSP que buscan una forma eficaz de hacerlo, nuestro script PowerShell 2.0 es una bendición, ya que automatiza la tarea y viene equipado con comprobaciones para asegurarte de que estás haciendo las cosas bien.

Próximos pasos

La creación de un equipo de TI próspero y eficaz requiere contar con una solución centralizada que se convierta en tu principal herramienta de prestación de servicios. NinjaOne permite a los equipos de TI supervisar, gestionar, proteger y dar soporte a todos sus dispositivos, estén donde estén, sin necesidad de complejas infraestructuras locales.

Conoce más sobre NinjaOne Endpoint Management, participa en una visita guiada en directo o prueba la plataforma NinjaOne de forma totalmente gratuita.

También te puede gustar

¿Listo para convertirte en un Ninja informático?

Descubre cómo NinjaOne puede ayudarte a simplificar las operaciones de TI.

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our 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 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).