Guarda una demo×
×

Guarda NinjaOne in azione!

Inviando questo modulo, accetto La politica sulla privacy di NinjaOne.

Come verificare attivazione di Windows e licenze in modo efficiente con PowerShell

Punti chiave

  • Controllo automatico della conformità: Lo script automatizza il processo di verifica dello stato di attivazione e di licenza di Windows, garantendo la conformità su più sistemi.
  • Identificazione e risoluzione degli errori: Lo script per verificare attivazione di Windows e licenze identifica gli errori specifici di attivazione di Windows e fornisce i passaggi per la risoluzione dei problemi, favorendo una rapida soluzione.
  • Efficienza nella gestione dell’IT: Automatizza un processo tradizionalmente manuale, facendo risparmiare tempo e risorse ai professionisti IT e agli MSP.
  • Supporta gli standard legali e di sicurezza: Contribuisce al mantenimento dei requisiti legali di licenza e garantisce che i sistemi ricevano gli aggiornamenti necessari per la sicurezza.
  • Versatile per i moderni sistemi Windows: Progettato per Windows 10, Windows Server 2016 e versioni successive, è adatto agli ambienti IT moderni.
  • Integrazione con gli strumenti di gestione IT: Può essere incorporato in soluzioni di gestione IT più ampie, come NinjaOne, per migliorare il monitoraggio e la gestione.
  • Output facile da comprendere: Lo script fornisce un output di facile comprensione, che lo rende accessibile ai professionisti IT con diversi livelli di competenza.

Introduzione

L’attivazione e la licenza di Windows sono componenti fondamentali per mantenere la legalità e la funzionalità dei sistemi Windows nell’ambiente IT. Assicurarsi che Windows sia correttamente autorizzato e attivato non è solo una questione legale, ma anche un prerequisito per ricevere importanti aggiornamenti e supporto. In questo contesto, gli script PowerShell emergono come potenti strumenti per i professionisti IT e i Managed Service Provider (MSP) per automatizzare e semplificare il processo di verifica dell’attivazione di Windows e dello stato delle licenze.

Background

Lo script PowerShell fornito è progettato per rilevare lo stato di attivazione e di licenza dei sistemi operativi Windows. È particolarmente utile negli ambienti in cui è necessario gestire più macchine e garantire che tutte siano conformi ai requisiti di licenza di Microsoft. Questo script è una manna per i professionisti IT e gli MSP, in quanto consente di identificare rapidamente le installazioni di Windows prive di licenza o non attivate, evitando così potenziali problemi legali e garantendo l’integrità del sistema.

Lo script per verificare attivazione di Windows e licenze

#Requires -Version 5.1

<#
.SYNOPSIS
    Condition script for detecting activation and license status of Windows.
.DESCRIPTION
    Condition script for detecting activation and license status of Windows.
    Exit codes:
    0 = Activated and Licensed
    2 = Unlicensed, but under a grace period
    3 = Not Activated and Unlicensed
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes: Renamed script
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/it/condizioni-utilizzo
    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 {
    # https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/dn502528(v=ws.11)
    $NotificationReasons = {
        [PSCustomObject]@{
            ErrorCode            = "0xC004C001"
            ErrorMessage         = "The activation server determined the specified product key is invalid"
            ActivationType       = "MAK"
            PossibleCause        = "An invalid MAK was entered."
            TroubleshootingSteps = "Verify that the key is the MAK provided by Microsoft. Contact the Microsoft Activation Call Center to verify that the MAK is valid."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004C003"
            ErrorMessage         = "The activation server determined the specified product key has been blocked"
            ActivationType       = "MAK"
            PossibleCause        = "The MAK is blocked on the activation server."
            TroubleshootingSteps = "Contact the Microsoft Activation Call Center to obtain a new MAK and install/activate the system."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004C008"
            ErrorMessage         = "The activation server reported that the product key has exceeded its unlock limit."
            ActivationType       = "KMS"
            PossibleCause        = "The KMS key has exceeded the activation limit."
            TroubleshootingSteps = "KMS host keys will activate up to 10 times on six different computers. If more activations are necessary, contact the Microsoft Activation Call Center."       
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004C020"
            ErrorMessage         = "The activation server reported that the Multiple Activation Key has exceeded its limit."
            ActivationType       = "MAK"
            PossibleCause        = "The MAK has exceeded the activation limit."
            TroubleshootingSteps = "MAKs by design have a limited number of activations. Contact the Microsoft Activation Call Center."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004C021"
            ErrorMessage         = "The activation server reported that the Multiple Activation Key extension limit has been exceeded."
            ActivationType       = "MAK"
            PossibleCause        = "The MAK has exceeded the activation limit."
            TroubleshootingSteps = "MAKs by design have a limited number of activations. Contact the Microsoft Activation Call Center."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004F009"
            ErrorMessage         = "The Software Protection Service reported that the grace period expired."
            ActivationType       = "MAK"
            PossibleCause        = "The grace period expired before the system was activated. Now, the system is in the Notifications state."
            TroubleshootingSteps = "See the section User Experience."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004F00F"
            ErrorMessage         = "The Software Licensing Server reported that the hardware ID binding is beyond level the of tolerance."
            ActivationType       = "MAK/KMS client/KMS host"
            PossibleCause        = "The hardware has changed or the drivers were updated on the system."
            TroubleshootingSteps = "MAK: Reactivate the system during the OOT grace period using either online or phone activation. KMS: Restart, or run slmgr.vbs /ato."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004F014"
            ErrorMessage         = "The Software Protection Service reported that the product key is not available"
            ActivationType       = "MAK/KMS client"
            PossibleCause        = "No product keys are installed on the system."
            TroubleshootingSteps = "Install a MAK product key, or install a KMS Setup key found in \\sources\\Product.ini on the installation media."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004F02C"
            ErrorMessage         = "The Software Protection Service reported that the format for the offline activation data is incorrect."
            ActivationType       = "MAK/KMS client"
            PossibleCause        = "The system has detected that the data entered during phone activation is not valid."
            TroubleshootingSteps = "Verify that the CID is correctly entered."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004F038"
            ErrorMessage         = "The Software Protection Service reported that the computer could not be activated. The count reported by your Key Management Service (KMS) is insufficient. Please contact your system administrator."
            ActivationType       = "KMS client"
            PossibleCause        = "The count on the KMS host is not high enough. The KMS count must be ≥5 for Windows Server or ≥25 for Windows client."
            TroubleshootingSteps = "More computers are needed in the KMS pool for KMS clients to activate. Run Slmgr.vbs /dli to get the current count on the KMS host."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004F039"
            ErrorMessage         = "The Software Protection Service reported that the computer could not be activated. The Key Management Service (KMS) is not enabled."
            ActivationType       = "KMS client"
            PossibleCause        = "This error occurs when a KMS request is not answered."
            TroubleshootingSteps = "Troubleshoot the network connection between the KMS host and the client. Make sure that TCP port 1688 (default) is not blocked by a firewall or otherwise filtered."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004F041"
            ErrorMessage         = "The Software Licensing Service determined that the Key Management Service (KMS) is not activated. KMS needs to be activated. Please contact system administrator."
            ActivationType       = "KMS client"
            PossibleCause        = "The KMS host is not activated."
            TroubleshootingSteps = "Activate the KMS host with either online or phone activation."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004F042"
            ErrorMessage         = "The Software Protection Service determined that the specified Key Management Service (KMS) cannot be used."
            ActivationType       = "KMS client"
            PossibleCause        = "Mismatch between the KMS client and the KMS host."
            TroubleshootingSteps = "This error occurs when a KMS client contacts a KMS host that cannot activate the client software. This can be common in mixed environments that contain application and operating system-specific KMS hosts, for example."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004F050"
            ErrorMessage         = "The Software Protection Service reported that the product key is invalid."
            ActivationType       = "KMS, KMS client, MAK"
            PossibleCause        = "This can be caused by a typo in the KMS key or by typing in a Beta key on a Released version of the operating system."
            TroubleshootingSteps = "Install the appropriate KMS key on the corresponding version of Windows. Check the spelling. If the key is being copied and pasted, make sure that em dashes have not been substituted for the dashes in the key."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004F051"
            ErrorMessage         = "The Software Protection Service reported that the product key is blocked."
            ActivationType       = "MAK/KMS"
            PossibleCause        = "The product key on the activation server is blocked by Microsoft."
            TroubleshootingSteps = "Obtain a new MAK/KMS key, install it on the system, and activate."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004F074"
            ErrorMessage         = "The Software Protection Service reported that the computer could not be activated. No Key Management Service (KMS) could be contacted. Please see the Application Event Log for additional information."
            ActivationType       = "KMS Client"
            PossibleCause        = "All KMS host systems  returned an error."
            TroubleshootingSteps = "Troubleshoot errors from each event ID 12288 associated with the activation attempt."
        }
        [PSCustomObject]@{
            ErrorCode            = "0xC004F06C"
            ErrorMessage         = "The Software Protection Service reported that the computer could not be activated. The Key Management Service (KMS) determined that the request timestamp is invalid."
            ActivationType       = "KMS client"
            PossibleCause        = "The system time on the client computer is too different from the time on the KMS host."
            TroubleshootingSteps = "Time sync is important to system and network security for a variety of reasons. Fix this issue by changing the system time on the client to sync with the KMS. Use of a Network Time Protocol (NTP) time source or Active Directory Domain Services for time synchronization is recommended. This issue uses UTP time and is independent of Time Zone selection."
        }
        [PSCustomObject]@{
            ErrorCode            = "0x80070005"
            ErrorMessage         = "Access denied. The requested action requires elevated privileges."
            ActivationType       = "KMS client/MAK/KMS host"
            PossibleCause        = "User Account Control (UAC) prohibits activation processes from running in a non-elevated command prompt."
            TroubleshootingSteps = "Run slmgr.vbs from an elevated command prompt. Right-click cmd.exe, and then click Run as Administrator."
        }
        [PSCustomObject]@{
            ErrorCode            = "0x8007232A"
            ErrorMessage         = "DNS server failure."
            ActivationType       = "KMS host"
            PossibleCause        = "The system has network or DNS issues."
            TroubleshootingSteps = "Troubleshoot network and DNS."
        }
        [PSCustomObject]@{
            ErrorCode            = "0x8007232B"
            ErrorMessage         = "DNS name does not exist."
            ActivationType       = "KMS client"
            PossibleCause        = "The KMS client cannot find KMS SRV RRs in DNS. If a KMS host does not exist on the network, a MAK should be installed."
            TroubleshootingSteps = "Confirm that a KMS host has been installed and DNS publishing is enabled (default). If DNS is unavailable, point the KMS client to the KMS host by using slmgr.vbs /skms \u003ckms_host_name\u003e. Optionally, obtain and install a MAK; then, activate the system. Finally, troubleshoot DNS."
        }
        [PSCustomObject]@{
            ErrorCode            = "0x800706BA"
            ErrorMessage         = "The RPC server is unavailable."
            ActivationType       = "KMS client"
            PossibleCause        = "Firewall settings are not configured on the KMS host, or DNS SRV records are stale."
            TroubleshootingSteps = "Ensure the Key Management Service firewall exception is enabled on the KMS host computer. Ensure that SRV records point to a valid KMS host. Troubleshoot network connections."
        }
        [PSCustomObject]@{
            ErrorCode            = "0x8007251D"
            ErrorMessage         = "No records found for given DNS query."
            ActivationType       = "KMS client"
            PossibleCause        = "The KMS client cannot find KMS SRV RRs in DNS."
            TroubleshootingSteps = "Troubleshoot network connections and DNS."
        }
    }.Invoke()
}
process {
    Write-Host ""

    $LicenseStatus = Get-CimInstance -ClassName "SoftwareLicensingProduct" -Filter "Name like 'Windows%'" -ErrorAction SilentlyContinue |
        Where-Object { $_.PartialProductKey } |
        Select-Object -ExpandProperty LicenseStatus

    $ActivationNumber = switch ($LicenseStatus) {
        0 { 3 }
        1 { 0 }
        2 { 2 }
        3 { 2 }
        4 { 3 }
        5 { 3 }
        6 { 2 }
        default { 3 }
    }

    $Result = cscript.exe C:\Windows\system32\slmgr.vbs -dli
    $Result | Select-Object -Skip 4 | Out-String | Write-Host
    $Notification = $Result -split [System.Environment]::NewLine | Where-Object { $_ -match "^Notification Reason: .*" }
    Write-Host ""
    if ($Notification) {
        $NotificationCode = $($($Notification -split ': ')[1] -split '\.')[0]
        Write-Host "[Error] KMS Activation Error Found."
        if ($NotificationCode -like "0xC004F200") { Write-Host "Non-Genuine" }
        elseif ($NotificationCode -like "0xC004F009") { Write-Host "Grace Time Expired" }
        else {
            $NotificationReasons | Where-Object { $_.ErrorCode -like "$NotificationCode" } | Out-String | Write-Host
        }
    }
    if ($Result -like "*Eval*") {
        Write-Host "Evaluation Licensed"
        exit 5 # Is Activated but is an Evaluation license
    }
    exit $ActivationNumber
}
end {
    
    
    
}

 

Accedi a oltre 700 script nel Dojo NinjaOne

Ottieni l’accesso

Analisi dettagliata

Lo script per verificare attivazione di Windows e licenze inizia definendo una serie di potenziali codici di errore e messaggi relativi all’attivazione di Windows. Questi sono incapsulati in un oggetto personalizzato di PowerShell, che fornisce informazioni dettagliate sulla natura dell’errore, sul tipo di attivazione (per esempio, MAK, KMS) e sui passaggi per la risoluzione dei problemi.

Nel blocco del processo, lo script per verificare attivazione di Windows e licenze esegue una serie di comandi:

  • Recupera lo stato delle licenze dei prodotti Windows utilizzando il cmdlet Get-CimInstance.
  • Lo stato della licenza viene quindi valutato attraverso un’istruzione switch, che lo traduce in un codice di uscita che rappresenta i diversi stati di attivazione e di licenza.
  • Lo script per verificare attivazione di Windows e licenze quindi esegue slmgr.vbs -dli, che fornisce informazioni dettagliate sull’attivazione di Windows e sullo stato delle licenze.
  • Lo script per verificare attivazione di Windows e licenze analizza l’output di slmgr.vbs per identificare eventuali errori di attivazione specifici e fornisce le informazioni di risoluzione dei problemi corrispondenti ottenendole dagli oggetti personalizzati definiti in precedenza.

Casi d’uso potenziali

Immagina un MSP che gestisce l’infrastruttura IT di un’azienda di medie dimensioni. Può pianificare l’esecuzione periodica di questo script per verificare attivazione di Windows e licenze su tutti i computer Windows. Se viene trovato un computer con un’installazione di Windows non attivata o priva di licenza, lo script può avvisare l’MSP, consentendogli di intraprendere prontamente un’azione correttiva.

Confronti

I metodi tradizionali di verifica dell’attivazione di Windows prevedono controlli manuali su ogni sistema o l’utilizzo di strumenti diversi, che possono richiedere molto tempo e risultare incoerenti. Questo script per verificare attivazione di Windows e licenze offre un approccio centralizzato e automatizzato, garantendo coerenza e risparmio di tempo.

Domande frequenti

  • Come si esegue questo script per verificare attivazione di Windows e licenze?
    • Esegui lo script in PowerShell come amministratore.
  • Questo script per verificare attivazione di Windows e licenze attiverà Windows per me?
    • No, controllerà solo lo stato di attivazione e fornirà i passaggi per la risoluzione dei problemi.
  • Questo script per verificare attivazione di Windows e licenze può essere eseguito su tutte le versioni di Windows?
    • È progettato per Windows 10, Windows Server 2016 e versioni successive.

Implicazioni

I sistemi Windows con licenza non corretta o non attivati possono rappresentare un rischio significativo per la sicurezza, in quanto potrebbero non ricevere gli aggiornamenti critici. Questo script per verificare attivazione di Windows e licenze aiuta a mantenere la conformità e gli standard di sicurezza all’interno di un’infrastruttura IT.

Raccomandazioni

  • Pianifica regolarmente l’esecuzione dello script per verificare attivazione di Windows e licenze su tutti i computer Windows della rete.
  • Controlla e agisci tempestivamente basandoti sui risultati dello script per mantenere la conformità.
  • Assicurati che i criteri di esecuzione di PowerShell consentano l’esecuzione degli script.

Considerazioni finali

Nel campo della gestione IT, strumenti come NinjaOne possono integrare questo script PowerShell fornendo una piattaforma completa per il monitoraggio, la gestione e l’automazione delle attività IT. L’integrazione di script come questo in una soluzione di gestione IT più ampia come NinjaOne può migliorare l’efficienza, garantire la conformità e mantenere l’integrità del sistema nell’infrastruttura IT di un’organizzazione.

Passi successivi

La creazione di un team IT efficiente ed efficace richiede una soluzione centralizzata che funga da principale strumento per la fornitura di servizi. NinjaOne consente ai team IT di monitorare, gestire, proteggere e supportare tutti i dispositivi, ovunque essi si trovino, senza la necessità di una complessa infrastruttura locale.

Per saperne di più su NinjaOne Endpoint Management, fai un tour dal vivo, o inizia la tua prova gratuita della piattaforma NinjaOne.

Ti potrebbe interessare anche

Termini e condizioni NinjaOne

Cliccando sul pulsante “Accetto” qui sotto, dichiari di accettare i seguenti termini legali e le nostre condizioni d’uso:

  • Diritti di proprietà: NinjaOne possiede e continuerà a possedere tutti i diritti, i titoli e gli interessi relativi allo script (compreso il copyright). NinjaOne ti concede una licenza limitata per l’utilizzo dello script in conformità con i presenti termini legali.
  • Limitazione d’uso: Puoi utilizzare lo script solo per legittimi scopi personali o aziendali interni e non puoi condividere lo script con altri soggetti.
  • Divieto di ripubblicazione: In nessun caso ti è consentito ripubblicare lo script in una libreria di script appartenente o sotto il controllo di un altro fornitore di software.
  • Esclusione di garanzia: Lo script viene fornito “così com’è” e “come disponibile”, senza garanzie di alcun tipo. NinjaOne non promette né garantisce che lo script sia privo di difetti o che soddisfi le tue esigenze o aspettative specifiche.
  • Assunzione del rischio: L’uso che farai dello script è da intendersi a tuo rischio. Riconosci che l’utilizzo dello script comporta alcuni rischi intrinseci, che comprendi e sei pronto ad assumerti.
  • Rinuncia e liberatoria: Non riterrai NinjaOne responsabile di eventuali conseguenze negative o indesiderate derivanti dall’uso dello script e rinuncerai a qualsiasi diritto legale o di equità e a qualsiasi rivalsa nei confronti di NinjaOne in relazione all’uso dello script.
  • EULA: Se sei un cliente NinjaOne, l’uso dello script è soggetto al Contratto di licenza con l’utente finale (EULA) applicabile.