Ver demo×
×

¡Vean a NinjaOne en acción!

Al enviar este formulario, acepto la política de privacidad de NinjaOne.

Cómo activar o desactivar la recopilación de datos de Windows 10 (script PowerShell)

En la era digital, la privacidad y la seguridad de los datos son primordiales. A medida que Windows 10 ha ido ganando popularidad, también lo ha hecho la preocupación por sus funciones de recopilación de datos. Para los profesionales de TI y los proveedores de servicios gestionados (MSP), comprender y controlar estas funciones es crucial. Este artículo profundiza en un script de PowerShell diseñado para activar o desactivar la función de recopilación de datos de Windows 10.

Antecedentes

Windows 10, al igual que muchos sistemas operativos modernos, incorpora funciones de telemetría y recopilación de datos con el objetivo de mejorar la experiencia del usuario mediante la recopilación de datos sobre patrones de uso, errores, etc. Sin embargo, por diversas razones, como la preocupación por la privacidad y el cumplimiento de la normativa, los profesionales de TI y los MSP a menudo necesitan controlar estas funciones. Nuestro script para desactivar la recopilación de datos de Windows 10 ofrece una forma simplificada de gestionar estos ajustes.

El script para desactivar la recopilación de datos de Windows 10

#Requires -Version 5.1

<#
.SYNOPSIS
    Enables or Disabled Windows 10 Linguistic Data Collection, Advertising ID, and Telemetry
.DESCRIPTION
    Enables or Disabled Windows 10 Linguistic Data Collection, Advertising ID, and Telemetry
.EXAMPLE
    No Params needed to Disable Windows 10 Linguistic Data Collection, Advertising ID, and Telemetry
.EXAMPLE
     -Enable
    Enables Linguistic Data Collection, Advertising ID, and Telemetry
.EXAMPLE
    PS C:> Set-Windows10KeyLogger.ps1
    Disables Windows 10 Linguistic Data Collection, Advertising ID, and Telemetry
.EXAMPLE
    PS C:> Set-Windows10KeyLogger.ps1 -Enable
    Enables Windows 10 Linguistic Data Collection, Advertising ID, and Telemetry
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10
    Release Notes:
    Initial Release
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/es/terminos-de-uso
    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).
.COMPONENT
    OSSecurity
#>

[CmdletBinding()]
param (
    [Parameter()]
    [Switch]
    $Enable
)

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
        { Write-Output $true }
        else
        { Write-Output $false }
    }
    function Set-ItemProp {
        param (
            $Path,
            $Name,
            $Value,
            [ValidateSet('DWord', 'QWord', 'String', 'ExpandedString', 'Binary', 'MultiString', 'Unknown')]
            $PropertyType = 'DWord'
        )
        New-Item -Path $Path -Force | Out-Null
        if ((Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue)) {
            Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false | Out-Null
        }
        else {
            New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false | Out-Null
        }
    }
    $Type = "DWORD"
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }

    $Value = if ($PSBoundParameters.ContainsKey("Enable") -and $Enable) { 1 }else { 0 }

    try {
        @(
            # Linguistic Data Collection
            [PSCustomObject]@{
                Path = "HKLM:SOFTWAREMicrosoftWindowsCurrentVersionPoliciesTextInput"
                Name = "AllowLinguisticDataCollection"
            }
            # Advertising ID
            [PSCustomObject]@{
                Path = "HKLM:SOFTWAREMicrosoftWindowsCurrentVersionAdvertisingInfo"
                Name = "Enabled"
            }
            # Telemetry
            [PSCustomObject]@{
                Path = "HKLM:SOFTWAREPoliciesMicrosoftWindowsDataCollection"
                Name = "AllowTelemetry"
            }
        ) | ForEach-Object {
            Set-ItemProp -Path $_.Path -Name $_.Name -Value $Value -PropertyType $Type
            Write-Host "$($_.Path)$($_.Name) set to $(Get-ItemPropertyValue -Path $_.Path -Name $_.Name)"
        }

        if ($PSBoundParameters.ContainsKey("Enable") -and $Enable) {
            Write-Host "Enabling DiagTrack Services"
            Get-Service -Name DiagTrack | Set-Service -StartupType Automatic | Start-Service
        }
        else { 
            Write-Host "Disabling DiagTrack Services"
            Get-Service -Name DiagTrack | Set-Service -StartupType Disabled | Stop-Service
        }

        Write-Host "DiagTrack Service status: $(Get-Service -Name DiagTrack | Select-Object -Property Status -ExpandProperty Status)"
        Write-Host "DiagTrack Service is set to: $(Get-Service -Name dmwappushservice | Select-Object -Property StartType -ExpandProperty StartType)"

        if ($PSBoundParameters.ContainsKey("Enable") -and $Enable) {
            Get-Service -Name dmwappushservice | Set-Service -StartupType Manual
        }
        else { 
            Get-Service -Name dmwappushservice | Set-Service -StartupType Disabled | Stop-Service
        }

        Write-Host "dmwappushservice Service status: $(Get-Service -Name dmwappushservice | Select-Object -Property Status -ExpandProperty Status)"
        Write-Host "dmwappushservice Service is set to: $(Get-Service -Name dmwappushservice | Select-Object -Property StartType -ExpandProperty StartType)"

        $tasks = "SmartScreenSpecific", "ProgramDataUpdater", "Microsoft Compatibility Appraiser", "AitAgent", "Proxy", "Consolidator",
        "KernelCeipTask", "BthSQM", "CreateObjectTask", "WinSAT", #"Microsoft-Windows-DiskDiagnosticDataCollector", # This is disabled by default
        "GatherNetworkInfo", "FamilySafetyMonitor", "FamilySafetyRefresh", "SQM data sender", "OfficeTelemetryAgentFallBack",
        "OfficeTelemetryAgentLogOn"
        
        if ($PSBoundParameters.ContainsKey("Enable") -and $Enable) {
            Write-Host "Enabling telemetry scheduled tasks"
            $tasks | ForEach-Object {
                Write-Host "Enabling $_ Scheduled Task"
                # Note: ErrorAction set to SilentlyContinue so as to skip over any missing tasks. Enable-ScheduledTask will still error if it can't be enabled.
                Get-ScheduledTask -TaskName $_ -ErrorAction SilentlyContinue | Enable-ScheduledTask
                $State = Get-ScheduledTask -TaskName $_ -ErrorAction SilentlyContinue | Select-Object State -ExpandProperty State
                Write-Host "Scheduled Task: $_ is $State"
            }
        }
        else { 
            Write-Host "Disabling telemetry scheduled tasks"
            $tasks | ForEach-Object {
                Write-Host "Disabling $_ Scheduled Task"
                # Note: ErrorAction set to SilentlyContinue so as to skip over any missing tasks. Disable-ScheduledTask will still error if it can't be disabled.
                Get-ScheduledTask -TaskName $_ -ErrorAction SilentlyContinue | Disable-ScheduledTask
                $State = Get-ScheduledTask -TaskName $_ -ErrorAction SilentlyContinue | Select-Object State -ExpandProperty State
                Write-Host "Scheduled Task: $_ is $State"
            }
        }
    }
    catch {
        Write-Error $_
        exit 1
    }
    
    gpupdate.exe /force
    exit 0
}
end {}

|

#Requires -Version 5.1

<#
.SYNOPSIS
    Enables or Disabled Windows 10 Linguistic Data Collection, Advertising ID, and Telemetry
.DESCRIPTION
    Enables or Disabled Windows 10 Linguistic Data Collection, Advertising ID, and Telemetry
.EXAMPLE
    No Params needed to Disable Windows 10 Linguistic Data Collection, Advertising ID, and Telemetry
.EXAMPLE
     -Enable
    Enables Linguistic Data Collection, Advertising ID, and Telemetry
.EXAMPLE
    PS C:> Set-Windows10KeyLogger.ps1
    Disables Windows 10 Linguistic Data Collection, Advertising ID, and Telemetry
.EXAMPLE
    PS C:> Set-Windows10KeyLogger.ps1 -Enable
    Enables Windows 10 Linguistic Data Collection, Advertising ID, and Telemetry
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10
    Release Notes:
    Initial Release
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).
.COMPONENT
    OSSecurity
#>

[CmdletBinding()]
param (
    [Parameter()]
    [Switch]
    $Enable
)

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
        { Write-Output $true }
        else
        { Write-Output $false }
    }
    function Set-ItemProp {
        param (
            $Path,
            $Name,
            $Value,
            [ValidateSet('DWord', 'QWord', 'String', 'ExpandedString', 'Binary', 'MultiString', 'Unknown')]
            $PropertyType = 'DWord'
        )
        New-Item -Path $Path -Force | Out-Null
        if ((Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue)) {
            Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false | Out-Null
        }
        else {
            New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false | Out-Null
        }
    }
    $Type = "DWORD"
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }

    $Value = if ($PSBoundParameters.ContainsKey("Enable") -and $Enable) { 1 }else { 0 }

    try {
        @(
            # Linguistic Data Collection
            [PSCustomObject]@{
                Path = "HKLM:SOFTWAREMicrosoftWindowsCurrentVersionPoliciesTextInput"
                Name = "AllowLinguisticDataCollection"
            }
            # Advertising ID
            [PSCustomObject]@{
                Path = "HKLM:SOFTWAREMicrosoftWindowsCurrentVersionAdvertisingInfo"
                Name = "Enabled"
            }
            # Telemetry
            [PSCustomObject]@{
                Path = "HKLM:SOFTWAREPoliciesMicrosoftWindowsDataCollection"
                Name = "AllowTelemetry"
            }
        ) | ForEach-Object {
            Set-ItemProp -Path $_.Path -Name $_.Name -Value $Value -PropertyType $Type
            Write-Host "$($_.Path)$($_.Name) set to $(Get-ItemPropertyValue -Path $_.Path -Name $_.Name)"
        }

        if ($PSBoundParameters.ContainsKey("Enable") -and $Enable) {
            Write-Host "Enabling DiagTrack Services"
            Get-Service -Name DiagTrack | Set-Service -StartupType Automatic | Start-Service
        }
        else { 
            Write-Host "Disabling DiagTrack Services"
            Get-Service -Name DiagTrack | Set-Service -StartupType Disabled | Stop-Service
        }

        Write-Host "DiagTrack Service status: $(Get-Service -Name DiagTrack | Select-Object -Property Status -ExpandProperty Status)"
        Write-Host "DiagTrack Service is set to: $(Get-Service -Name dmwappushservice | Select-Object -Property StartType -ExpandProperty StartType)"

        if ($PSBoundParameters.ContainsKey("Enable") -and $Enable) {
            Get-Service -Name dmwappushservice | Set-Service -StartupType Manual
        }
        else { 
            Get-Service -Name dmwappushservice | Set-Service -StartupType Disabled | Stop-Service
        }

        Write-Host "dmwappushservice Service status: $(Get-Service -Name dmwappushservice | Select-Object -Property Status -ExpandProperty Status)"
        Write-Host "dmwappushservice Service is set to: $(Get-Service -Name dmwappushservice | Select-Object -Property StartType -ExpandProperty StartType)"

        $tasks = "SmartScreenSpecific", "ProgramDataUpdater", "Microsoft Compatibility Appraiser", "AitAgent", "Proxy", "Consolidator",
        "KernelCeipTask", "BthSQM", "CreateObjectTask", "WinSAT", #"Microsoft-Windows-DiskDiagnosticDataCollector", # This is disabled by default
        "GatherNetworkInfo", "FamilySafetyMonitor", "FamilySafetyRefresh", "SQM data sender", "OfficeTelemetryAgentFallBack",
        "OfficeTelemetryAgentLogOn"
        
        if ($PSBoundParameters.ContainsKey("Enable") -and $Enable) {
            Write-Host "Enabling telemetry scheduled tasks"
            $tasks | ForEach-Object {
                Write-Host "Enabling $_ Scheduled Task"
                # Note: ErrorAction set to SilentlyContinue so as to skip over any missing tasks. Enable-ScheduledTask will still error if it can't be enabled.
                Get-ScheduledTask -TaskName $_ -ErrorAction SilentlyContinue | Enable-ScheduledTask
                $State = Get-ScheduledTask -TaskName $_ -ErrorAction SilentlyContinue | Select-Object State -ExpandProperty State
                Write-Host "Scheduled Task: $_ is $State"
            }
        }
        else { 
            Write-Host "Disabling telemetry scheduled tasks"
            $tasks | ForEach-Object {
                Write-Host "Disabling $_ Scheduled Task"
                # Note: ErrorAction set to SilentlyContinue so as to skip over any missing tasks. Disable-ScheduledTask will still error if it can't be disabled.
                Get-ScheduledTask -TaskName $_ -ErrorAction SilentlyContinue | Disable-ScheduledTask
                $State = Get-ScheduledTask -TaskName $_ -ErrorAction SilentlyContinue | Select-Object State -ExpandProperty State
                Write-Host "Scheduled Task: $_ is $State"
            }
        }
    }
    catch {
        Write-Error $_
        exit 1
    }
    
    gpupdate.exe /force
    exit 0
}
end {}

 

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

Obtén acceso

Análisis detallado

El script para desactivar la recopilación de datos de Windows 10 es un cmdlet de PowerShell que activa la recopilación de datos lingüísticos, el ID de publicidad y la telemetría de Windows 10. Aquí tienes un desglose paso a paso:

  1. Requisitos previos: el script requiere PowerShell versión 5.1.
  2. Parámetros: el script acepta un modificador opcional -Enable. Si se proporciona, activa las funciones de recopilación de datos; de lo contrario, las desactiva.
  3. Funciones:
    1. Test-IsElevated: comprueba si el script se está ejecutando con privilegios de administrador.
    2. Set-ItemProp: restablece o crea un valor de clave de registro.
  4. Proceso:
    1. En primer lugar, el script comprueba si se dispone de privilegios de administrador. Si no está presente, sale.
    2. A continuación, determina si activar o desactivar las funciones en función del interruptor -Enable.
    3. El script modifica claves de registro específicas correspondientes a la recogida de datos lingüísticos, ID de publicidad y telemetría.
    4. También gestiona los servicios DiagTrack y dmwappushservice, relacionados con la telemetría.
    5. Por último, activa varias tareas programadas relacionadas con la telemetría.
  5. Ejecución: el script concluye forzando una actualización de la política de grupo.

Posibles casos de uso

Imagínate un MSP que gestione las TI de un proveedor de servicios sanitarios. Debido a la normativa HIPAA, deben garantizar una fuga de datos mínima. Con este script para desactivar la recopilación de datos de Windows 10, el MSP puede desactivar rápidamente todas las funciones de recopilación de datos en todos los equipos Windows 10 de la red, lo que garantiza el cumplimiento y mejora la privacidad de los datos de los pacientes.

Comparaciones

Aunque existen herramientas basadas en GUI y métodos manuales para alternar estos ajustes, este script para desactivar la recopilación de datos de Windows 10 ofrece una solución más eficiente, repetible y escalable. Los métodos manuales pueden llevar mucho tiempo y ser propensos a errores, sobre todo en varias máquinas. Las herramientas GUI pueden no ofrecer la granularidad o las capacidades de automatización que ofrece un script PowerShell.

Preguntas frecuentes

  • ¿Puedo ejecutar este script en versiones anteriores de Windows?
    No, este script está diseñado específicamente para Windows 10.
  • ¿Necesito privilegios de administrador para ejecutar el script para desactivar la recopilación de datos de Windows 10?
    Sí, el script requiere derechos de administrador para modificar las claves del registro y gestionar los servicios.

Implicaciones

El uso de este script para desactivar la recopilación de datos de Windows 10 puede mejorar significativamente la privacidad de los datos, especialmente en sectores con normativas estrictas. Sin embargo, deshabilitar algunas características podría limitar ciertas funcionalidades o mecanismos de respuesta en Windows 10. Los profesionales de TI deben sopesar las ventajas frente a las posibles limitaciones.

Recomendaciones

  • Haz siempre una copia de seguridad de la configuración del registro antes de realizar cambios.
  • Prueba el script en un entorno controlado antes de desplegarlo ampliamente.
  • Revisa y actualiza periódicamente los scripts para adaptarlos a los cambios de las futuras actualizaciones de Windows 10.

Reflexiones finales

Para los profesionales de TI y los MSP, herramientas como NinjaOne pueden ser muy valiosas para gestionar y supervisar los entornos de TI. Cuando se combinan con scripts como el que comentamos, pueden garantizar una infraestructura informática segura, conforme a las normas y eficaz. A medida que evolucionen las funciones de recopilación de datos de Windows 10, será esencial contar con un conjunto de herramientas y una base de conocimientos sólidos.

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.

Obtén más información sobre NinjaOne Endpoint Management, echa un vistazo a un tour en vivo o comienza tu prueba gratuita de la plataforma NinjaOne.

Quizá también te interese…

Términos y condiciones de NinjaOne

Al hacer clic en el botón «Acepto» que aparece a continuación, estás aceptando los siguientes términos legales, así como nuestras Condiciones de uso:

  • Derechos de propiedad: NinjaOne posee y seguirá poseyendo todos los derechos, títulos e intereses sobre el script (incluidos los derechos de autor). NinjaOne concede al usuario una licencia limitada para utilizar el script de acuerdo con estos términos legales.
  • Limitación de uso: sólo podrás utilizar el script para tus legítimos fines personales o comerciales internos, y no podrás compartirlo con terceros.
  • Prohibición de republicación: Bajo ninguna circunstancia está permitido volver a publicar el script en ninguna biblioteca de scripts que pertenezca o esté bajo el control de cualquier otro proveedor de software.
  • Exclusión de garantía: El script se proporciona «»tal cual» y «según disponibilidad», sin garantía de ningún tipo. NinjaOne no promete ni garantiza que el script esté libre de defectos o que satisfaga las necesidades o expectativas específicas del usuario.
  • Asunción de riesgos: El uso que el usuario haga del script corre por su cuenta y riesgo. El usuario reconoce que existen ciertos riesgos inherentes al uso del script, y entiende y asume cada uno de esos riesgos.
  • Renuncia y exención: El usuario no hará responsable a NinjaOne de cualquier consecuencia adversa o no deseada que resulte de su uso del script y renuncia a cualquier derecho o recurso legal o equitativo que pueda tener contra NinjaOne en relación con su uso del script.
  • CLUF: Si el usuario es cliente de NinjaOne, su uso del script está sujeto al Contrato de Licencia para el Usuario Final (CLUF).