Dynamically Determine a DSC Configuration Name Inside a Configuration
I ran across a scenario where I needed to reference the name of the configuration inside the configuration. I was looking for an automatic variable that contained this information, however I was unable to locate one searching online or by asking colleagues. The suggestions I received were to call the Get-PSCallStack
cmdlet or use the $MyInvocation
automatic variable.
To test these options, I created a small config and wrote the output of the options using Write-Verbose
.
Get-PSCallStack
Configuration MyConfig
{
Write-Verbose -Message ( Get-PSCallStack | Format-Table -AutoSize | Out-String )
}
MyConfig -Verbose
VERBOSE:
Command Arguments
------- ---------
{}
Configuration {ArgsToBody=System.Collections.Hashtable, Name=MyConfig, ResourceModuleTuplesToImport=, Body=...
MyConfig {Verbose=True}
<ScriptBlock> {}
The configuration name "MyConfig" is the third item in the array, and therefore would be referenced like `(Get-PSCallStack)[2].Command`. Not terribly bad, but not as simple as I would like.
$MyInvocation
Configuration MyConfig
{
Write-Verbose -Message ( $MyInvocation | Format-List -Property * | Out-String )
}
MyConfig -Verbose
VERBOSE:
MyCommand :
BoundParameters : {}
UnboundArguments : {}
ScriptLineNumber : 7
OffsetInLine : 1
HistoryId : 14
ScriptName :
Line : MyConfig -Verbose
PositionMessage : At line:7 char:1
+ MyConfig -Verbose
+ ~~~~~~~~~~~~~~~~~
PSScriptRoot :
PSCommandPath :
InvocationName :
PipelineLength : 0
PipelinePosition : 0
ExpectingInput : False
CommandOrigin : Internal
DisplayScriptPosition :
The "Line" property of $MyInvocation contains the full command that was executed. I could use some string manipulation to retrieve the name of the configuration, however Get-PSCallStack
is simpler at this point.
$MyTypeName
At this point, Get-PSCallStack
looks like the best option, however I was still curious if there is an automatic variable that contains only the configuration name. To investigate the variables available inside the configuration, I executed the following:
Configuration MyConfig
{
Write-Verbose -Message ( Get-Variable | Where-Object -FilterScript { $_.Value -match '^MyConfig$' } | Out-String )
}
MyConfig -Verbose
VERBOSE:
Name Value
---- -----
MyTypeName MyConfig
Success! There is an automatic variable called $MyTypeName
that contains only my configuration name. This is the easy button option I was looking for.