Risoluzione dei problemi relativi a DSC

Si applica a: Windows PowerShell 4.0, Windows PowerShell 5.1

Questo articolo contiene le istruzioni per la risoluzione di errori comuni.

Dipendenza da WinRM

Desired State Configuration (DSC) in Windows PowerShell dipende da WinRM. WinRM non è abilitato per impostazione predefinita in Windows Server 2008 R2 e Windows 7. Per abilitare WinRM, eseguire Set-WSManQuickConfig in una sessione di Windows PowerShell con privilegi elevati.

Uso di Get-DscConfigurationStatus

Il cmdlet Get-DscConfigurationStatus ottiene informazioni di alto livello sullo stato di configurazione da un nodo di destinazione. Il comando restituisce un oggetto avanzato che include informazioni generali sul fatto che l'esecuzione della configurazione sia stata eseguita correttamente o meno. È possibile esaminare l'oggetto per scoprire i dettagli sull'esecuzione della configurazione, ad esempio:

  • Ogni risorsa non riuscita.
  • Qualsiasi risorsa che ha richiesto un riavvio.
  • Meta-Configuration impostazioni al momento dell'esecuzione della configurazione.

Il set di parametri seguente restituisce informazioni sullo stato per l'ultima esecuzione della configurazione:

Get-DscConfigurationStatus [-CimSession <CimSession[]>]
                           [-ThrottleLimit <int>]
                           [-AsJob]
                           [<CommonParameters>]

Il set di parametri seguente restituisce le informazioni sullo stato per ogni esecuzione della configurazione:

Get-DscConfigurationStatus -All
                           [-CimSession <CimSession[]>]
                           [-ThrottleLimit <int>]
                           [-AsJob]
                           [<CommonParameters>]

Esempio

PS C:\> $Status = Get-DscConfigurationStatus

PS C:\> $Status

Status         StartDate                Type            Mode    RebootRequested        NumberOfResources
------        ---------                ----            ----    ---------------        -----------------
Failure        11/24/2015  3:44:56     Consistency        Push    True                36

PS C:\> $Status.ResourcesNotInDesiredState

ConfigurationName     :    MyService
DependsOn             :
ModuleName            :    PSDesiredStateConfiguration
ModuleVersion         :    1.1
PsDscRunAsCredential  :
ResourceID            :    [File]ServiceDll
SourceInfo            :    c:\git\CustomerService\Configs\MyCustomService.ps1::5::34::File
DurationInSeconds     :    0.19
Error                 :    SourcePath must be accessible for current configuration. The related file/directory is:
                           \\Server93\Shared\contosoApp.dll. The related ResourceID is [File]ServiceDll
FinalState            :
InDesiredState        :    False
InitialState          :
InstanceName          :    ServiceDll
RebootRequested       :    False
ResourceName          :    File
StartDate             :    11/24/2015  3:44:56
PSComputerName        :

Lo script non viene eseguito: uso di log DSC per diagnosticare gli errori di script

Come tutti i software Windows, DSC registra gli errori e gli eventi nei log disponibili per la revisione in Visualizzatore eventi. Esaminando questi registri è possibile comprendere perché un'operazione specifica non è riuscita e come evitare l'errore in futuro. Per semplificare il rilevamento degli errori durante la creazione, usare la risorsa log DSC per tenere traccia dello stato di avanzamento della configurazione nel registro eventi di Analisi DSC.

Dove sono i registri eventi DSC?

In Visualizzatore eventi gli eventi DSC si trovano in: Registri applicazioni e servizi/Microsoft/Windows/Desired State Configuration

È possibile eseguire il cmdlet di PowerShell corrispondente, Get-WinEvent, per visualizzare i log eventi:

PS C:\> Get-WinEvent -LogName "Microsoft-Windows-Dsc/Operational"

   ProviderName: Microsoft-Windows-DSC

TimeCreated                     Id LevelDisplayName Message
-----------                     -- ---------------- -------
11/17/2014 10:27:23 PM        4102 Information      Job {02C38626-D95A-47F1-9DA2-C1D44A7128E7} :

Il nome del log primario di DSC è Microsoft-Windows-DSC>> (altri nomi di log in Windows non sono visualizzati qui per brevità). Il nome primario viene aggiunto al nome del canale per creare il nome completo del log.

Il motore DSC usa principalmente tre tipi di registri: operativi, analitici e di debug. Poiché i log analitici e di debug non sono abilitati per impostazione predefinita, è necessario abilitarli in Visualizzatore eventi. Per eseguire questa operazione:

  1. Aprire Visualizzatore eventi in uno dei due casi:

    • Digitazione Show-EventLog in Windows PowerShell
    • Selezionando il pulsante Start, quindi Pannello di controllo, strumenti di amministrazione e quindi Visualizzatore eventi.
  2. Nel menu Visualizza nel Visualizzatore eventi selezionare Mostra log analitici e di debug.

    Il nome del log per il canale analitico è Microsoft-Windows-Dsc/Analytice il canale di debug è Microsoft-Windows-Dsc/Debug.

È anche possibile usare l'utilità wevtutil per abilitare i log, come illustrato nell'esempio seguente.

wevtutil.exe set-log "Microsoft-Windows-Dsc/Analytic" /q:true /e:true

In alternativa, usare PowerShell e .NET per abilitare i log, come illustrato nell'esempio seguente:

$logName = 'Microsoft-Windows-Dsc/Analytic'
$log = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration $logName
$log.IsEnabled = $true
$log.SaveChanges()

Cosa contengono i registri DSC?

DSC registra tre canali di log diversi in base all'importanza del messaggio. Il log operativo in DSC include tutti i messaggi di errore ed è utile per identificare un problema. Il log analitico ha un volume maggiore di eventi e può identificare dove si sono verificati errori. Questo canale include anche tutti i messaggi dettagliati generati. Il log di debug include log che consentono di comprendere come si sono verificati gli errori. I messaggi di evento DSC iniziano con un ID processo che rappresenta in modo univoco un'operazione DSC. L'esempio seguente tenta di ottenere il messaggio dal primo evento registrato nel log DSC operativo.

PS C:\> $AllDscOpEvents = Get-WinEvent -LogName "Microsoft-Windows-Dsc/Operational"
PS C:\> $FirstOperationalEvent = $AllDscOpEvents[0]
PS C:\> $FirstOperationalEvent.Message
Job {02C38626-D95A-47F1-9DA2-C1D44A7128E7} :
Consistency engine was run successfully.

DSC registra gli eventi con una struttura che consente all'utente di raccogliere eventi da un processo DSC. La struttura è analoga alla seguente:

Job ID : <Guid>
<Event Message>

Raccolta di eventi da una singola operazione DSC

I registri eventi DSC contengono eventi generati da diverse operazioni DSC. Tuttavia, in genere si è interessati ai dettagli per un'operazione specifica. Tutti i log DSC possono essere raggruppati in base alla proprietà ID processo univoca per ogni operazione DSC. L'ID processo viene visualizzato come primo valore della proprietà in tutti gli eventi DSC. I passaggi seguenti illustrano come riunire tutti gli eventi in una struttura di matrice raggruppata.

<##########################################################################
 Step 1 : Enable analytic and debug DSC channels (Operational channel is enabled by default)
###########################################################################>

wevtutil.exe set-log "Microsoft-Windows-Dsc/Analytic" /q:true /e:true
wevtutil.exe set-log "Microsoft-Windows-Dsc/Debug" /q:True /e:true

<##########################################################################
 Step 2 : Perform the required DSC operation (Below is an example, you could run any DSC operation instead)
###########################################################################>

Get-DscLocalConfigurationManager

<##########################################################################
Step 3 : Collect all DSC Logs, from the Analytic, Debug and Operational channels
###########################################################################>

$DscEvents=[System.Array](Get-WinEvent "Microsoft-Windows-Dsc/Operational") `
         + [System.Array](Get-WinEvent "Microsoft-Windows-Dsc/Analytic" -Oldest) `
         + [System.Array](Get-WinEvent "Microsoft-Windows-Dsc/Debug" -Oldest)


<##########################################################################
 Step 4 : Group all logs based on the job ID
###########################################################################>
$SeparateDscOperations = $DscEvents | Group {$_.Properties[0].value}

In questo caso, la variabile $SeparateDscOperations include i log raggruppati in base agli ID processo. Ogni elemento della matrice di questa variabile rappresenta un gruppo di eventi registrati da un'operazione DSC diversa e consente l'accesso ad altre informazioni sui registri.

PS C:\> $SeparateDscOperations

Count Name                      Group
----- ----                      -----
   48 {1A776B6A-5BAC-11E3-BF... {System.Diagnostics.Eventing.Reader.EventLogRecord, System.Diagnostics....
   40 {E557E999-5BA8-11E3-BF... {System.Diagnostics.Eventing.Reader.EventLogRecord, System.Diagnostics....

PS C:\> $SeparateDscOperations[0].Group

   ProviderName: Microsoft-Windows-DSC

TimeCreated                     Id LevelDisplayName Message
-----------                     -- ---------------- -------
12/2/2013 3:47:29 PM          4115 Information      Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4198 Information      Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4114 Information      Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4102 Information      Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4098 Warning          Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4098 Warning          Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4176 Information      Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4182 Information      Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4182 Information      Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4182 Information      Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4182 Information      Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4182 Information      Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4182 Information      Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4182 Information      Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...
12/2/2013 3:47:29 PM          4182 Information      Job {1A776B6A-5BAC-11E3-BF41-00155D553612} : ...

È possibile estrarre i dati nella variabile $SeparateDscOperations usando Where-Object. Di seguito sono riportati cinque scenari in cui è possibile estrarre i dati per la risoluzione dei problemi di DSC:

1: Errori relativi alle operazioni

Tutti gli eventi hanno livelli di gravità. Queste informazioni sono utili per identificare gli eventi di errore:

PS C:\> $SeparateDscOperations | Where-Object {$_.Group.LevelDisplayName -contains "Error"}

Count Name                      Group
----- ----                      -----
   38 {5BCA8BE7-5BB6-11E3-BF... {System.Diagnostics.Eventing.Reader.EventLogRecord, System.Diagnostics....

2: Dettagli delle operazioni eseguite nell'ultima mezz'ora

TimeCreated, una proprietà di ogni evento di Windows, indica l'ora di creazione dell'evento. Il confronto di questa proprietà con un particolare oggetto data/ora è utile per filtrare tutti gli eventi:

PS C:\> $DateLatest = (Get-Date).AddMinutes(-30)
PS C:\> $SeparateDscOperations | Where-Object {$_.Group.TimeCreated -gt $DateLatest}

Count Name                      Group
----- ----                      -----
    1 {6CEC5B09-5BB0-11E3-BF... {System.Diagnostics.Eventing.Reader.EventLogRecord}

3: Messaggi dell'operazione più recente

L'operazione più recente viene archiviata nel primo indice del gruppo di matrici $SeparateDscOperations. Eseguendo una query relativa ai messaggi del gruppo con indice 0, vengono restituiti tutti i messaggi per l'operazione più recente:

PS C:\> $SeparateDscOperations[0].Group.Message
Job {5BCA8BE7-5BB6-11E3-BF41-00155D553612} :
Running consistency engine.
Job {1A776B6A-5BAC-11E3-BF41-00155D553612} :
Configuration is sent from computer NULL by user sid S-1-5-18.
Job {1A776B6A-5BAC-11E3-BF41-00155D553612} :
Displaying messages from built-in DSC resources:
 WMI channel 1
 ResourceID:
 Message : [INCH-VM]:                            [] Starting consistency engine.
Job {1A776B6A-5BAC-11E3-BF41-00155D553612} :
Displaying messages from built-in DSC resources:
 WMI channel 1
 ResourceID:
 Message : [INCH-VM]:                            [] Consistency check completed.

4: Messaggi di errore registrati per operazioni recenti non riuscite

$SeparateDscOperations[0].Group ha il set di eventi per l'operazione più recente. Eseguire il cmdlet Where-Object per filtrare gli eventi in base al nome visualizzato del livello. I risultati vengono archiviati nella variabile $myFailedEvent, che può essere analizzata più in dettaglio per ottenere il messaggio di evento:

PS C:\> $myFailedEvent = ($SeparateDscOperations[0].Group |
    Where-Object {$_.LevelDisplayName -eq "Error"})

PS C:\> $myFailedEvent.Message

Job {5BCA8BE7-5BB6-11E3-BF41-00155D553612} :
DSC Engine Error :
 Error Message Current configuration does not exist. Execute Start-DscConfiguration command with
 -Path parameter to specify a configuration file and create a current configuration first.
Error Code : 1

5: Tutti gli eventi generati per un ID processo specifico.

$SeparateDscOperations è una matrice di gruppi, ognuno con il nome come ID processo univoco. Eseguendo il cmdlet Where-Object, è possibile estrarre i gruppi di eventi con un ID processo specifico:

PS C:\> ($SeparateDscOperations | Where-Object {$_.Name -eq $jobX} ).Group

   ProviderName: Microsoft-Windows-DSC

TimeCreated                     Id LevelDisplayName Message
-----------                     -- ---------------- -------
12/2/2013 4:33:24 PM          4102 Information      Job {847A5619-5BB2-11E3-BF41-00155D553612} : ...
12/2/2013 4:33:24 PM          4168 Information      Job {847A5619-5BB2-11E3-BF41-00155D553612} : ...
12/2/2013 4:33:24 PM          4146 Information      Job {847A5619-5BB2-11E3-BF41-00155D553612} : ...
12/2/2013 4:33:24 PM          4120 Information      Job {847A5619-5BB2-11E3-BF41-00155D553612} : ...

Uso di xDscDiagnostics per analizzare i registri DSC

xDscDiagnostics è un modulo di PowerShell costituito da alcune funzioni che consentono di analizzare gli errori di DSC nel computer in uso. Queste funzioni consentono di identificare tutti gli eventi locali delle operazioni DSC precedenti o gli eventi DSC nei computer remoti. In questo caso, il termine operazione DSC definisce una singola esecuzione DSC univoca dall'inizio alla fine. Ad esempio, Test-DscConfiguration sarebbe un'operazione DSC distinta. Analogamente, tutti gli altri cmdlet in DSC, ad esempio Get-DscConfiguration e Start-DscConfiguration, sono identificabili come operazioni DSC separate. Per altre informazioni sulle funzioni di diagnostica, vedere xDscDiagnostics.

Acquisizione dei dettagli delle operazioni DSC

La Get-xDscOperation funzione consente di trovare i risultati delle operazioni DSC eseguite in uno o più computer. La funzione restituisce un oggetto con la raccolta di eventi prodotti da ogni operazione DSC. Nell'output seguente, ad esempio, sono stati eseguiti tre comandi. Il primo ha avuto esito positivo e gli altri due esito negativo. L'output di Get-xDscOperation riepiloga questi risultati.

PS C:\DiagnosticsTest> Get-xDscOperation
ComputerName   SequenceId TimeCreated           Result   JobID                                 AllEvents
------------   ---------- -----------           ------   -----                                 ---------
SRV1   1          6/23/2016 9:37:52 AM  Failure  9701aadf-395e-11e6-9165-00155d390509  {@{Message=; TimeC...
SRV1   2          6/23/2016 9:36:54 AM  Failure  7e8e2d6e-395c-11e6-9165-00155d390509  {@{Message=; TimeC...
SRV1   3          6/23/2016 9:36:54 AM  Success  af72c6aa-3960-11e6-9165-00155d390509  {@{Message=Operati...

È possibile ottenere risultati solo per le operazioni più recenti specificando il parametro Più recente :

PS C:\DiagnosticsTest> Get-xDscOperation -Newest 5
ComputerName   SequenceId TimeCreated           Result   JobID                                 AllEvents
------------   ---------- -----------           ------   -----                                 ---------
SRV1   1          6/23/2016 4:36:54 PM  Success                                        {@{Message=; TimeC...
SRV1   2          6/23/2016 4:36:54 PM  Success  5c06402b-399b-11e6-9165-00155d390509  {@{Message=Operati...
SRV1   3          6/23/2016 4:36:54 PM  Success                                        {@{Message=; TimeC...
SRV1   4          6/23/2016 4:36:54 PM  Success  5c06402a-399b-11e6-9165-00155d390509  {@{Message=Operati...
SRV1   5          6/23/2016 4:36:51 PM  Success                                        {@{Message=; TimeC...

Acquisizione dei dettagli degli eventi DSC

Il cmdlet Trace-xDscOperation restituisce un oggetto contenente una raccolta di eventi, i relativi tipi e l'output del messaggio generato da un'operazione DSC specifica. In genere, quando si rileva un errore in una delle operazioni che usano Get-xDscOperation, è necessario tracciare tale operazione per trovare gli eventi che hanno causato un errore.

Usare il parametro SequenceID per ottenere gli eventi per un'operazione specifica in un computer specifico. Ad esempio, se si specifica 9 come SequenceID, Trace-xDscOperation ottiene la traccia per l'operazione DSC al nono posto dopo l'ultima operazione:

PS C:\DiagnosticsTest> Trace-xDscOperation -SequenceID 9
ComputerName   EventType    TimeCreated           Message
------------   ---------    -----------           -------
SRV1   OPERATIONAL  6/24/2016 10:51:52 AM Operation Consistency Check or Pull started by user sid S-1-5-20 from computer NULL.
SRV1   OPERATIONAL  6/24/2016 10:51:52 AM Running consistency engine.
SRV1   OPERATIONAL  6/24/2016 10:51:52 AM The local configuration manager is updating the PSModulePath to WindowsPowerShell\Modules;C:\Prog...
SRV1   OPERATIONAL  6/24/2016 10:51:53 AM  Resource execution sequence :: [WindowsFeature]DSCServiceFeature, [xDSCWebService]PSDSCPullServer.
SRV1   OPERATIONAL  6/24/2016 10:51:54 AM Consistency engine was run successfully.
SRV1   OPERATIONAL  6/24/2016 10:51:54 AM Job runs under the following LCM setting. ...
SRV1   OPERATIONAL  6/24/2016 10:51:54 AM Operation Consistency Check or Pull completed successfully.

Passare il GUID assegnato a una specifica operazione DSC, come restituito dal cmdlet Get-xDscOperation, per ottenere i dettagli degli eventi per l'operazione DSC:

PS C:\DiagnosticsTest> Trace-xDscOperation -JobID 9e0bfb6b-3a3a-11e6-9165-00155d390509

ComputerName   EventType    TimeCreated           Message
------------   ---------    -----------           -------
SRV1   OPERATIONAL  6/24/2016 11:36:56 AM Operation Consistency Check or Pull started by user sid S-1-5-20 from computer NULL.
SRV1   ANALYTIC     6/24/2016 11:36:56 AM Deleting file from C:\Windows\System32\Configuration\DSCEngineCache.mof
SRV1   OPERATIONAL  6/24/2016 11:36:56 AM Running consistency engine.
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]:                            [] Starting consistency engine.
SRV1   ANALYTIC     6/24/2016 11:36:56 AM Applying configuration from C:\Windows\System32\Configuration\Current.mof.
SRV1   ANALYTIC     6/24/2016 11:36:56 AM Parsing the configuration to apply.
SRV1   OPERATIONAL  6/24/2016 11:36:56 AM  Resource execution sequence :: [WindowsFeature]DSCServiceFeature, [xDSCWebService]PSDSCPullServer.
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]: LCM:  [ Start  Resource ]  [[WindowsFeature]DSCServiceFeature]
SRV1   ANALYTIC     6/24/2016 11:36:56 AM Executing operations for PS DSC resource MSFT_RoleResource with resource name [WindowsFeature]DSC...
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]: LCM:  [ Start  Test     ]  [[WindowsFeature]DSCServiceFeature]
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]:                            [[WindowsFeature]DSCServiceFeature] The operation 'Get...
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]:                            [[WindowsFeature]DSCServiceFeature] The operation 'Get...
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]: LCM:  [ End    Test     ]  [[WindowsFeature]DSCServiceFeature] True in 0.3130 sec...
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]: LCM:  [ End    Resource ]  [[WindowsFeature]DSCServiceFeature]
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]: LCM:  [ Start  Resource ]  [[xDSCWebService]PSDSCPullServer]
SRV1   ANALYTIC     6/24/2016 11:36:56 AM Executing operations for PS DSC resource MSFT_xDSCWebService with resource name [xDSCWebService]P...
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]: LCM:  [ Start  Test     ]  [[xDSCWebService]PSDSCPullServer]
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]:                            [[xDSCWebService]PSDSCPullServer] Check Ensure
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]:                            [[xDSCWebService]PSDSCPullServer] Check Port
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]:                            [[xDSCWebService]PSDSCPullServer] Check Physical Path ...
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]:                            [[xDSCWebService]PSDSCPullServer] Check State
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]:                            [[xDSCWebService]PSDSCPullServer] Get Full Path for We...
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]: LCM:  [ End    Test     ]  [[xDSCWebService]PSDSCPullServer] True in 0.0160 seconds.
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]: LCM:  [ End    Resource ]  [[xDSCWebService]PSDSCPullServer]
SRV1   VERBOSE      6/24/2016 11:36:56 AM [SRV1]:                            [] Consistency check completed.
SRV1   ANALYTIC     6/24/2016 11:36:56 AM Deleting file from C:\Windows\System32\Configuration\DSCEngineCache.mof
SRV1   OPERATIONAL  6/24/2016 11:36:56 AM Consistency engine was run successfully.
SRV1   OPERATIONAL  6/24/2016 11:36:56 AM Job runs under the following LCM setting. ...
SRV1   OPERATIONAL  6/24/2016 11:36:56 AM Operation Consistency Check or Pull completed successfully.
SRV1   ANALYTIC     6/24/2016 11:36:56 AM Deleting file from C:\Windows\System32\Configuration\DSCEngineCache.mof

Si noti che, poiché Trace-xDscOperation aggrega gli eventi dai log analitici, di debug e operativi, viene richiesto di abilitare questi log.

In alternativa, è possibile raccogliere informazioni sugli eventi salvando l'output di Trace-xDscOperation in una variabile. È possibile usare i comandi seguenti per visualizzare tutti gli eventi per un'operazione DSC specifica.

PS C:\DiagnosticsTest> $Trace = Trace-xDscOperation -SequenceID 4

PS C:\DiagnosticsTest> $Trace.Event

Vengono visualizzati gli stessi risultati del Get-WinEvent cmdlet, ad esempio nell'output seguente:

   ProviderName: Microsoft-Windows-DSC

TimeCreated                     Id LevelDisplayName Message
-----------                     -- ---------------- -------
6/23/2016 1:36:53 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.
6/23/2016 1:36:53 AM          4343 Information      The DscTimer has successfully run LCM method PerformRequiredConfigurationChecks with flag 5.
6/23/2016 2:07:00 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.
6/23/2016 2:07:01 AM          4343 Information      The DscTimer has successfully run LCM method PerformRequiredConfigurationChecks with flag 5.
6/23/2016 2:36:55 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.
6/23/2016 2:36:56 AM          4343 Information      The DscTimer has successfully run LCM method PerformRequiredConfigurationChecks with flag 5.
6/23/2016 3:06:55 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.
6/23/2016 3:06:55 AM          4343 Information      The DscTimer has successfully run LCM method PerformRequiredConfigurationChecks with flag 5.
6/23/2016 3:36:55 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.
6/23/2016 3:36:55 AM          4343 Information      The DscTimer has successfully run LCM method PerformRequiredConfigurationChecks with flag 5.
6/23/2016 4:06:53 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.
6/23/2016 4:06:53 AM          4343 Information      The DscTimer has successfully run LCM method PerformRequiredConfigurationChecks with flag 5.
6/23/2016 4:36:52 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.
6/23/2016 4:36:53 AM          4343 Information      The DscTimer has successfully run LCM method PerformRequiredConfigurationChecks with flag 5.
6/23/2016 5:06:52 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.
6/23/2016 5:06:53 AM          4343 Information      The DscTimer has successfully run LCM method PerformRequiredConfigurationChecks with flag 5.
6/23/2016 5:36:54 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.
6/23/2016 5:36:54 AM          4343 Information      The DscTimer has successfully run LCM method PerformRequiredConfigurationChecks with flag 5.
6/23/2016 6:06:52 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.
6/23/2016 6:06:53 AM          4343 Information      The DscTimer has successfully run LCM method PerformRequiredConfigurationChecks with flag 5.
6/23/2016 6:36:56 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.
6/23/2016 6:36:57 AM          4343 Information      The DscTimer has successfully run LCM method PerformRequiredConfigurationChecks with flag 5.
6/23/2016 7:06:52 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.
6/23/2016 7:06:53 AM          4343 Information      The DscTimer has successfully run LCM method PerformRequiredConfigurationChecks with flag 5.
6/23/2016 7:36:53 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.
6/23/2016 7:36:54 AM          4343 Information      The DscTimer has successfully run LCM method PerformRequiredConfigurationChecks with flag 5.
6/23/2016 8:06:54 AM          4312 Information      The DscTimer is running LCM method PerformRequiredConfigurationChecks with the flag set to 5.

Idealmente, è consigliabile usare prima di tutto Get-xDscOperation per elencare le ultime esecuzioni della configurazione DSC nei computer. A questo scopo, è possibile esaminare qualsiasi singola operazione specificando sequenceID o JobID con Trace-xDscOperation per scoprire cosa ha fatto dietro le quinte.

Acquisizione degli eventi per un computer remoto

Utilizzare il parametro ComputerName del cmdlet Trace-xDscOperation per acquisire i dettagli dell'evento in un computer remoto. Prima di procedere, è necessario creare una regola firewall per consentire l'amministrazione remota nel computer remoto:

New-NetFirewallRule -Name "Service RemoteAdmin" -DisplayName "Remote" -Action Allow

Ora è possibile specificare il computer nella chiamata a Trace-xDscOperation:

Trace-xDscOperation -ComputerName SRV2 -Credential Get-Credential -SequenceID 5
ComputerName   EventType    TimeCreated           Message
------------   ---------    -----------           -------
SRV2   OPERATIONAL  6/24/2016 11:36:56 AM Operation Consistency Check or Pull started by user sid S-1-5-20 f...
SRV2   ANALYTIC     6/24/2016 11:36:56 AM Deleting file from C:\Windows\System32\Configuration\DSCEngineCach...
SRV2   OPERATIONAL  6/24/2016 11:36:56 AM Running consistency engine.
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]:                            [] Starting consistency...
SRV2   ANALYTIC     6/24/2016 11:36:56 AM Applying configuration from C:\Windows\System32\Configuration\Curr...
SRV2   ANALYTIC     6/24/2016 11:36:56 AM Parsing the configuration to apply.
SRV2   OPERATIONAL  6/24/2016 11:36:56 AM  Resource execution sequence :: [WindowsFeature]DSCServiceFeature,...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]: LCM:  [ Start  Resource ]  [[WindowsFeature]DSCSer...
SRV2   ANALYTIC     6/24/2016 11:36:56 AM Executing operations for PS DSC resource MSFT_RoleResource with re...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]: LCM:  [ Start  Test     ]  [[WindowsFeature]DSCSer...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]:                            [[WindowsFeature]DSCSer...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]:                            [[WindowsFeature]DSCSer...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]: LCM:  [ End    Test     ]  [[WindowsFeature]DSCSer...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]: LCM:  [ End    Resource ]  [[WindowsFeature]DSCSer...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]: LCM:  [ Start  Resource ]  [[xDSCWebService]PSDSCP...
SRV2   ANALYTIC     6/24/2016 11:36:56 AM Executing operations for PS DSC resource MSFT_xDSCWebService with ...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]: LCM:  [ Start  Test     ]  [[xDSCWebService]PSDSCP...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]:                            [[xDSCWebService]PSDSCP...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]:                            [[xDSCWebService]PSDSCP...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]:                            [[xDSCWebService]PSDSCP...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]:                            [[xDSCWebService]PSDSCP...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]:                            [[xDSCWebService]PSDSCP...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]: LCM:  [ End    Test     ]  [[xDSCWebService]PSDSCP...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]: LCM:  [ End    Resource ]  [[xDSCWebService]PSDSCP...
SRV2   VERBOSE      6/24/2016 11:36:56 AM [SRV2]:                            [] Consistency check co...
SRV2   ANALYTIC     6/24/2016 11:36:56 AM Deleting file from C:\Windows\System32\Configuration\DSCEngineCach...
SRV2   OPERATIONAL  6/24/2016 11:36:56 AM Consistency engine was run successfully.
SRV2   OPERATIONAL  6/24/2016 11:36:56 AM Job runs under the following LCM setting. ...
SRV2   OPERATIONAL  6/24/2016 11:36:56 AM Operation Consistency Check or Pull completed successfully.
SRV2   ANALYTIC     6/24/2016 11:36:56 AM Deleting file from C:\Windows\System32\Configuration\DSCEngineCach...

Le risorse non vengono aggiornate: come reimpostare la cache

Il motore DSC memorizza nella cache le risorse implementate come modulo di PowerShell, per garantire maggiore efficienza. Tuttavia, questo può causare problemi quando si crea una risorsa e lo si testa contemporaneamente perché DSC carica la versione memorizzata nella cache fino al riavvio del processo. Per fare in modo che DSC carichi la versione più recente, è necessario terminare in modo esplicito il processo che ospita il motore DSC.

Analogamente, quando si esegue , dopo aver aggiunto e modificato una risorsa personalizzata, la modifica potrebbe non essere eseguita Start-DscConfigurationa meno che, o fino a quando il computer viene riavviato. Questo perché DSC viene eseguito nel processo host del provider WMI (WmiPrvSE) e in genere sono presenti molte istanze di WmiPrvSE in esecuzione contemporaneamente. Quando si riavvia, il processo host viene riavviato e cancella la cache.

Per riciclare la configurazione e cancellare la cache senza riavviare il computer, è necessario arrestare e quindi riavviare il processo host. Questo può essere per ogni istanza, in cui si identifica il processo, arrestarlo e riavviarlo. In alternativa, è possibile usare DebugMode, come illustrato di seguito, per ricaricare la risorsa PowerShell DSC.

Per identificare il processo che ospita il motore DSC, elencare l'ID processo di WmiPrvSE, che ospita il motore DSC. Quindi, per aggiornare il provider, arrestare il WmiPrvSE processo usando i comandi seguenti e quindi eseguire Start-DscConfiguration di nuovo.

###
### find the process that is hosting the DSC engine
###
$CimParameters = @{
    ClassName = 'Msft_Providers'
    Filter    = "provider='dsctimer' OR provider='dsccore'"
}
$dscProcessID = Get-CimInstance @CimParameters |
    Select-Object -ExpandProperty HostProcessIdentifier

###
### Stop the process
###
Get-Process -Id $dscProcessID | Stop-Process

Uso di DebugMode

È possibile configurare Gestione configurazione locale per DSC in modo da usare DebugMode per cancellare sempre la cache quando il processo host viene riavviato. Se impostato su $true, il motore ricarica sempre la risorsa DSC di PowerShell. Dopo aver scritto la risorsa, è possibile ripristinarla $false e il motore ripristina il comportamento dei moduli nella memorizzazione nella cache dei moduli.

Di seguito è illustrato in che modo DebugMode può aggiornare automaticamente la cache. Si analizzi prima di tutto la configurazione predefinita:

Get-DscLocalConfigurationManager
AllowModuleOverwrite           : False
CertificateID                  :
ConfigurationID                :
ConfigurationMode              : ApplyAndMonitor
ConfigurationModeFrequencyMins : 30
Credential                     :
DebugMode                      : {None}
DownloadManagerCustomData      :
DownloadManagerName            :
LocalConfigurationManagerState : Ready
RebootNodeIfNeeded             : False
RefreshFrequencyMins           : 15
RefreshMode                    : PUSH
PSComputerName                 :

È possibile notare che DebugMode è None.

Per la dimostrazione di DebugMode, usare la risorsa di PowerShell seguente:

function Get-TargetResource {
    param (
        [Parameter(Mandatory)] $onlyProperty
    )

    $Path = "$env:SystemDrive\OutputFromTestProviderDebugMode.txt"

    return @{
        onlyProperty = Get-Content -Path $Path
    }
}
function Set-TargetResource {
    param (
        [Parameter(Mandatory)] $onlyProperty
    )

    "1" | Out-File -PSPath "$env:SystemDrive\OutputFromTestProviderDebugMode.txt"
}
function Test-TargetResource {
    param (
        [Parameter(Mandatory)]
        $onlyProperty
    )

    return $false
}

Creare ora una configurazione denominata TestProviderDebugMode:

Configuration ConfigTestDebugMode
{
    Import-DscResource -Name TestProviderDebugMode
    Node localhost
    {
        TestProviderDebugMode test
        {
            onlyProperty = "blah"
        }
    }
}
ConfigTestDebugMode

Il contenuto del file $env:SystemDrive\OutputFromTestProviderDebugMode.txt è 1.

Aggiornare quindi il codice del provider usando lo script seguente:

$newResourceOutput = Get-Random -Minimum 5 -Maximum 30
$OutputPath = "C:\Program Files\WindowsPowerShell\Modules\MyPowerShellModules\DSCResources\TestProviderDebugMode\TestProviderDebugMode.psm1"
$content = @"
function Get-TargetResource {
    param (
        [Parameter(Mandatory)] `$onlyProperty
    )

    `$Path = "$env:SystemDrive\OutputFromTestProviderDebugMode.txt"
    return @{
        onlyProperty = Get-Content -Path $Path
    }
}
function Set-TargetResource {
    param (
        [Parameter(Mandatory)] `$onlyProperty
    )

    "$newResourceOutput" | Out-File -PSPath C:\OutputFromTestProviderDebugMode.txt
}
function Test-TargetResource {
    param (
        [Parameter(Mandatory)] `$onlyProperty
    )

    return `$false
}
"@ | Out-File -FilePath $OutputPath

Questo script genera un numero casuale e aggiorna il codice del provider. Con DebugMode impostato su false, i contenuti del file $env:SystemDrive\OutputFromTestProviderDebugMode.txt non sono mai cambiati.

Ora, impostare DebugMode su ForceModuleImport nello script di configurazione:

LocalConfigurationManager
{
    DebugMode = "ForceModuleImport"
}

Quando si esegue di nuovo lo script, si noti che il contenuto del file è diverso ogni volta. È possibile eseguirlo Get-DscConfiguration per controllarlo. Il frammento di codice seguente mostra il risultato di due esecuzioni. I risultati potrebbero essere diversi quando si esegue lo script.

PS C:\> Get-DscConfiguration -CimSession (New-CimSession localhost)

onlyProperty                            PSComputerName
------------                            --------------
20                                      localhost

PS C:\> Get-DscConfiguration -CimSession (New-CimSession localhost)

onlyProperty                            PSComputerName
------------                            --------------
14                                      localhost

DSC restituisce un errore di tipo "restituito un codice di risposta non previsto InternalServerError" durante la registrazione con il server di pull Windows

Quando si applica una metaconfigurazione a un server per registrarla con un'istanza di Windows Pull Server, è possibile che venga visualizzato l'errore seguente.

Registration of the Dsc Agent with the server https://<serverfqdn>:8080/PSDSCPullServer.svc failed. The underlying error is: The attempt to register Dsc Agent with AgentId <ID> with the server
https://<serverfqdn>:8080/PSDSCPullServer.svc/Nodes(AgentId='<ID>') returned unexpected response code InternalServerError. .
    + CategoryInfo          : InvalidResult: (root/Microsoft/...gurationManager:String) [], CimException
    + FullyQualifiedErrorId : RegisterDscAgentUnsuccessful,Microsoft.PowerShell.DesiredStateConfiguration.Commands.RegisterDscAgentCommand
    + PSComputerName        : <computername>

Ciò può verificarsi quando il certificato usato nel server per crittografare il traffico ha un nome comune (CN) diverso dal nome DNS usato dal nodo per risolvere l'URL. Aggiornare l'istanza del server di pull Windows in modo che usi un certificato con il nome corretto.

Errore durante l'esecuzione di Sysprep dopo l'applicazione di una configurazione DSC

Quando si tenta di eseguire Sysprep per generalizzare un Windows Server dopo aver applicato una configurazione DSC, è possibile che venga visualizzato l'errore seguente.

SYSPRP LaunchDll:Failure occurred while executing 'DscCore.dll,SysPrep_Cleanup', returned error code 0x2

La generalizzazione di un server dopo la configurazione di Windows PowerShell Desired State Configuration non è uno scenario supportato. In alternativa, applicare le configurazioni a Windows al termine della fase di specializzazione dell'installazione di Windows.

Vedere anche

Concetti

Risorse aggiuntive