Solución de problemas de DSC

Se aplica a: Windows PowerShell 4.0, Windows PowerShell 5.1

En este artículo se proporcionan instrucciones para la solución de errores comunes.

Dependencia de WinRM

La configuración de estado deseado (DSC) de Windows PowerShell depende de WinRM. WinRM no está habilitado de forma predeterminada en Windows Server 2008 R2 y Windows 7. Para habilitar WinRM, ejecute Set-WSManQuickConfig en una sesión de Windows PowerShell con permisos elevados.

Uso de Get-DscConfigurationStatus

El cmdlet Get-DscConfigurationStatus obtiene información acerca del estado de la configuración de un nodo de destino. El comando devuelve un objeto enriquecido que incluye información de alto nivel sobre si la ejecución de la configuración se realizó correctamente o no. Ya puede adentrarse en el objeto para descubrir los detalles sobre la configuración de ejecución como:

  • Todos los recursos con errores.
  • Cualquier recurso que solicitó un reinicio.
  • Meta-Configuration configuración en el momento de la ejecución de la configuración.

El siguiente conjunto de parámetros devuelve la información de estado de la última ejecución de la configuración:

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

El siguiente conjunto de parámetros devuelve la información de estado de cada ejecución de configuración:

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

Ejemplo

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        :

El script no se ejecuta: uso de registros de DSC para diagnosticar errores de scripts

Al igual que todo el software de Windows, DSC registra errores y eventos en los registros que están disponibles para su revisión en Visor de eventos. Examinar estos registros puede ayudarle a entender el motivo del error de una operación determinada y cómo evitar los errores en el futuro. Para facilitar el seguimiento de errores a medida que crea, use el recurso registro de DSC para realizar un seguimiento del progreso de la configuración en el registro de eventos de DSC Analytics.

¿Dónde se encuentran los registros de eventos de DSC?

En el Visor de eventos, los eventos de DSC se encuentran en: Registros de aplicaciones y servicios/Microsoft/Windows/Desired State Configuration

Puede ejecutar el cmdlet de PowerShell correspondiente, Get-WinEvent, para ver los registros de eventos:

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} :

El nombre de registro principal de DSC es Microsoft-Windows-DSC>> (otros nombres de registro en Windows no se muestran aquí para mayor brevedad). El nombre principal se anexa al nombre del canal para crear el nombre de registro completo.

El motor de DSC escribe principalmente en tres tipos de registros: registros operativos, analíticos y de depuración. Dado que los registros analíticos y de depuración no están habilitados de forma predeterminada, debe habilitarlos en Visor de eventos. Para ello, siga estos pasos:

  1. Abra Visor de eventos por:

    • Escribir Show-EventLog en Windows PowerShell
    • Al seleccionar el botón Inicio, Panel de control, luego Herramientas administrativas y, a continuación, Visor de eventos.
  2. En el menú Ver del Visor de eventos, seleccione Mostrar registros analíticos y de depuración.

    El nombre del registro para el canal analítico es Microsoft-Windows-Dsc/Analyticy el canal de depuración es Microsoft-Windows-Dsc/Debug.

También puede usar la utilidad wevtutil para habilitar los registros, como se muestra en el ejemplo siguiente.

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

O bien, use PowerShell y .NET para habilitar los registros, como se muestra en el ejemplo siguiente:

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

¿Qué contienen los registros de DSC?

DSC registra en tres canales de registro diferentes en función de la importancia del mensaje. El registro operativo de DSC incluye todos los mensajes de error y es útil para identificar un problema. El registro analítico tiene un mayor volumen de eventos y puede identificar dónde se produjeron los errores. Este canal también incluye los mensajes detallados emitidos. El registro de depuración tiene registros que pueden ayudarle a comprender cómo se produjeron los errores. Los mensajes de eventos de DSC comienzan con un identificador de trabajo que representa de forma única una operación de DSC. En el ejemplo siguiente se intenta obtener el mensaje del primer evento registrado en el registro de 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 eventos con una estructura que permite al usuario recopilar eventos de un trabajo de DSC. La estructura es como sigue:

Job ID : <Guid>
<Event Message>

Recopilación de eventos de una operación de DSC única

Los registros de eventos de DSC contienen los eventos que han generado diferentes operaciones de DSC. Sin embargo, normalmente le interesan los detalles de una operación específica. Todos los registros de DSC se pueden agrupar mediante la propiedad de identificador de trabajo única para cada operación de DSC. El identificador de trabajo se muestra como el primer valor de propiedad en todos los eventos de DSC. En los siguientes pasos se explica cómo acumular todos los eventos en una estructura de matriz agrupada.

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

Aquí, la variable $SeparateDscOperations incluye registros agrupados por los identificadores de trabajo. Cada elemento de la matriz de esta variable representa un grupo de eventos que ha registrado otra operación de DSC, lo que permite el acceso a más información sobre los registros.

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} : ...

Puede extraer los datos en la variable $SeparateDscOperations con Where-Object. A continuación se muestran cinco escenarios en los que es posible que quiera extraer datos para solucionar problemas de DSC:

1: errores de operaciones

Todos los eventos tienen niveles de gravedad. Esta información es útil para identificar los eventos de error:

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: detalles de las operaciones ejecutadas en última media hora

TimeCreated, una propiedad de todos los eventos de Windows, indica la hora en que se creó el evento. Comparar esta propiedad con un objeto de fecha y hora determinado es útil para filtrar todos los eventos:

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: mensajes de la operación más reciente

La operación más reciente se almacena en el primer índice del grupo de matrices $SeparateDscOperations. Si se consultan los mensajes del grupo del índice 0, se devuelven todos los mensajes para la operación más reciente:

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: mensajes de error registrados para operaciones con errores recientes

$SeparateDscOperations[0].Group tiene el conjunto de eventos para la operación más reciente. Ejecute el cmdlet Where-Object para filtrar los eventos según su nombre para mostrar del nivel. Los resultados se almacenan en la variable $myFailedEvent, que se puede analizar en más profundidad para obtener el mensaje de 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: todos los eventos que ha generado un identificador de trabajo determinado

$SeparateDscOperations es una matriz de grupos, que cada uno tiene el nombre como identificador de trabajo único. Al ejecutar el cmdlet Where-Object, puede extraer esos grupos de eventos que tienen un identificador de trabajo determinado:

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 de xDscDiagnostics para analizar registros de DSC

xDscDiagnostics es un módulo de PowerShell que consta de varias funciones que pueden ayudar a analizar los errores de DSC en la máquina. Estas funciones pueden ayudarle a identificar todos los eventos locales de operaciones anteriores de DSC o eventos de DSC en equipos remotos. En este caso, el término operación de DSC define una única ejecución de DSC desde su principio hasta su final. Por ejemplo, Test-DscConfiguration sería una operación de DSC independiente. Del mismo modo, todos los demás cmdlets de DSC, como Get-DscConfiguration y Start-DscConfiguration, se identifican como operaciones de DSC independientes. Para obtener más información sobre las funciones de diagnóstico, vea xDscDiagnostics.

Obtención de detalles de las operaciones de DSC

La Get-xDscOperation función permite encontrar los resultados de las operaciones de DSC que se ejecutan en uno o varios equipos. La función devuelve un objeto que tiene la colección de eventos generados por cada operación de DSC. Por ejemplo, en la salida siguiente, se ejecutaron tres comandos. El primero se realizó correctamente y los otros dos no. La salida de Get-xDscOperation resume estos resultados.

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...

Puede obtener resultados solo para las operaciones más recientes especificando el parámetro Newest :

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...

Obtención de detalles de los eventos de DSC

El cmdlet Trace-xDscOperation devuelve un objeto que contiene una colección de eventos, sus tipos de eventos y la salida del mensaje generado a partir de una determinada operación de DSC. Normalmente, cuando encuentre un error en cualquiera de las operaciones que usan Get-xDscOperation, realizaría un seguimiento de esa operación para encontrar los eventos que provocaron un error.

Utilice el parámetro SequenceID para obtener los eventos de una operación específica de un equipo concreto. Por ejemplo, si en SequenceID especifica 9, Trace-xDscOperation obtiene el seguimiento de la operación de DSC que era la novena desde la última operación:

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.

Pase el GUID asignado a una operación de DSC concreta (el que ha devuelto el cmdlet Get-xDscOperation) para obtener los detalles de los eventos de dicha operación de 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

Tenga en cuenta que, dado Trace-xDscOperation que agrega eventos de los registros analíticos, de depuración y operativos, le pide que habilite estos registros.

Como alternativa, puede recopilar información sobre los eventos si guarda el resultado de Trace-xDscOperation en una variable. Puede utilizar los comandos siguientes para mostrar todos los eventos de una operación de DSC concreta.

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

PS C:\DiagnosticsTest> $Trace.Event

Esto muestra los mismos resultados que el Get-WinEvent cmdlet, como en la salida siguiente:

   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, primero deberá utilizar Get-xDscOperation para enumerar las últimas configuraciones DSC que se han ejecutado en las máquinas. Después de esto, puede examinar cualquier operación única especificando su SequenceID o JobID con Trace-xDscOperation para descubrir lo que hizo en segundo plano.

Obtención de eventos de un equipo remoto

Utilice el parámetro ComputerName del cmdlet Trace-xDscOperation para obtener los detalles de los eventos de un equipo remoto. Para ello, antes es preciso crear una regla de firewall que permita la administración remota en el equipo remoto:

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

A partir de ahí se puede especificar dicho equipo en la llamada 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...

Los recursos no se actualizan: procedimiento para restablecer la memoria caché

El motor de DSC almacena en caché los recursos implementados como un módulo de PowerShell por motivos de eficiencia. Sin embargo, esto puede causar problemas al crear un recurso y probarlo simultáneamente porque DSC carga la versión almacenada en caché hasta que se reinicia el proceso. La única manera de conseguir que DSC cargue la versión más reciente es detener explícitamente el proceso que hospeda el motor de DSC.

Del mismo modo, al ejecutar Start-DscConfiguration, después de agregar y modificar un recurso personalizado, la modificación puede no ejecutarse a menos que, o hasta, se reinicie el equipo. Esto se debe a que DSC se ejecuta en el proceso de host del proveedor WMI (WmiPrvSE) y, normalmente, hay muchas instancias de WmiPrvSE que se ejecutan a la vez. Al reiniciar, el proceso de host se reinicia y borra la memoria caché.

Para reciclar la configuración de correctamente y borrar la memoria caché sin necesidad de reiniciar, debe detener y después reiniciar el proceso del host. Esto puede ser por instancia, mediante el cual se identifica el proceso, se detiene y se reinicia. O bien, puede usar DebugMode, como se muestra a continuación, para volver a cargar el recurso de DSC de PowerShell.

Para identificar el proceso que hospeda el motor de DSC, enumere el identificador de proceso de WmiPrvSE, que hospeda el motor de DSC. A continuación, para actualizar el proveedor, detenga el WmiPrvSE proceso mediante los comandos siguientes y vuelva a ejecutarse Start-DscConfiguration .

###
### 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 de DebugMode

Puede configurar el administrador de configuración de local (LCM) de DSC para que utilice DebugMode y siempre se borre la memoria caché cuando se reinicie el proceso de host. Cuando se establece $trueen , hace que el motor siempre vuelva a cargar el recurso de DSC de PowerShell. Una vez que haya terminado de escribir el recurso, puede volver a establecerlo en $false y el motor vuelve a su comportamiento de almacenar en caché los módulos.

A continuación se incluye una demostración donde se aprecia cómo DebugMode puede actualizar automáticamente la memoria caché. En primer lugar, echemos un vistazo a la configuración predeterminada:

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

Puede ver que DebugMode es None.

Para configurar la demostración de DebugMode, utilice el siguiente recurso de PowerShell:

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
}

Ahora, cree una configuración denominada TestProviderDebugMode:

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

El contenido del archivo $env:SystemDrive\OutputFromTestProviderDebugMode.txt es 1.

Ahora, actualice el código del proveedor mediante el siguiente script:

$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

Este script genera un número aleatorio y actualiza el código del proveedor. Con DebugMode establecido en false, el contenido del archivo $env:SystemDrive\OutputFromTestProviderDebugMode.txt no cambia nunca.

Ahora, establezca DebugMode en ForceModuleImport en el script de configuración:

LocalConfigurationManager
{
    DebugMode = "ForceModuleImport"
}

Al volver a ejecutar el script, tenga en cuenta que el contenido del archivo es diferente cada vez. Puede ejecutar Get-DscConfiguration para comprobarlo. El fragmento de código siguiente muestra el resultado de dos ejecuciones más. Los resultados pueden ser diferentes al ejecutar el 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 devuelve el código de respuesta inesperado "InternalServerError" al registrarse con Windows Pull Server

Al aplicar una metaconfiguración a un servidor para registrarla con una instancia de Windows Pull Server, es posible que reciba el siguiente error.

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>

Esto puede ocurrir cuando el certificado usado en el servidor para cifrar el tráfico tiene un nombre común (CN) distinto del nombre DNS usado por el nodo para resolver la dirección URL. Actualice la instancia de Windows Pull Server para que use un certificado con un nombre corregido.

Error al ejecutar Sysprep tras aplicar una configuración de DSC

Al intentar ejecutar Sysprep para generalizar una instancia de Windows Server después de aplicar una configuración de DSC, es posible que reciba el siguiente error.

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

La generalización de un servidor después de configurarlo mediante Windows PowerShell Desired State Configuration no es un escenario admitido. En su lugar, aplique los valores a Windows una vez completada la fase de especialización de la configuración de Windows.

Consulte también

Conceptos

Otros recursos