Giter Club home page Giter Club logo

dscparser's Introduction

DSC Parser

Receives a DSC configuration script (.ps1) as an input, and parses all containes resources and properties into logical PSObject. Usage scenario include: analyzing DSC config for best practices, getting quick stats out of a config, etc.

Installation

DSCParser is available from the PowerShell Gallery, simply run:

Install-Module DSCParser

Usage

$DSCObjects = ConvertTo-DSCObject -Path $PSScriptRoot\..\Tests\Templates\Template1.ps1 -IncludeComments $true
$DSCObjects | Format-Table

dscparser's People

Contributors

microsoft-github-policy-service[bot] avatar microsoftopensource avatar mpiederiet avatar msftgits avatar nikcharlebois avatar przemyslawklys avatar ricmestre avatar ykuijs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dscparser's Issues

Variables in array of values are concatenated in error when parsing

When parsing a DSC resource that contains variables in the array of values for one of the keys, the variable name ends up concatenated with the next member of the array in error.

For example, parsing the ExcludeGroups of the AADConditionalAccessPolicy resource below (additional properties removed for brevity):

Node localhost
    {
        AADConditionalAccessPolicy CA01
        {
            ExcludeGroups = @($env:BreakGlassGroup,$env:MMDServiceAccountGroup,"MSG_DEV_CASpecificExclusion");
        }
    }

Results in parsed results like this:

    "ExcludeGroups":  [
                          "$env:BreakGlassGroup,env:MMDServiceAccountGroup",
                          "MSG_DEV_CASpecificExclusion"
                      ]

Rather than like this:

    "ExcludeGroups":  [
                          "$env:BreakGlassGroup",
                          "$env:MMDServiceAccountGroup",
                          "MSG_DEV_CASpecificExclusion"
                      ]

The problem appears to be with the Do Until loop at row 256 in Modules/DSCParser.psm1:

Do {
    $currentPropertyIndex++
    $ValueToSet += $group[$CurrentPropertyIndex].Content
} until (($group[$CurrentPropertyIndex + 1].Type -eq 'Operator' -and $group[$CurrentPropertyIndex + 1].Content -eq ',') -or $group[$currentPropertyIndex + 1].Type -eq 'GroupEnd')

Because this iterates once through the loop before checking the Until condition, it appends the ',' operator and the content of the following variable before it stops looping.

From testing it looks as though this can be solved by using a While loop instead:

While (-not (($group[$CurrentPropertyIndex + 1].Type -eq 'Operator' -and $group[$CurrentPropertyIndex + 1].Content -eq ',') -or $group[$currentPropertyIndex + 1].Type -eq 'GroupEnd')) {
    $currentPropertyIndex++
    $ValueToSet += $group[$CurrentPropertyIndex].Content
}

This checks the condition before looping, so encounters the ',' operator and ends the loop. It still supports the advanced variables such as $Test.Nested.Variable, which I think was the original intention of the Do Until loop.

ConvertTo-DscObject busted again with nested properties in some cases

It seems that sometimes ConvertTo-DscObject still misbehaves, take a look at the blueprint at the bottom then check this, the Settings property inside $Resource has other properties inside that should be actually be nested inside Settings.SettingInstance (such as Value or odataType)

PS C:\> $Resource.Settings  

Name                           Value
----                           -----
CIMInstance                    MSFT_MicrosoftGraphdeviceManagementConfigurationSetting
SettingInstance                {CIMInstance, choiceSettingValue}
Value                          device_vendor_msft_policy_config_updatev83diff~policy~cat_edgeupdate~cat_applications_pol_defaultcreatedesktopshortcut_0
SettingDefinitionId            device_vendor_msft_policy_config_updatev83diff~policy~cat_edgeupdate~cat_applications_pol_defaultcreatedesktopshortcut
odataType                      #microsoft.graph.deviceManagementConfigurationChoiceSettingInstance

But in this case Settings.SettingInstance is actually empty where it shouldn't.

PS C:\> $Resource.Settings.SettingInstance

Name                           Value
----                           -----
CIMInstance                    MSFT_MicrosoftGraphDeviceManagementConfigurationSettingInstance
choiceSettingValue

Blueprint

# Generated with Microsoft365DSC version 1.23.705.1
# For additional information on how to use Microsoft365DSC, please visit https://aka.ms/M365DSC
param (
    [parameter()]
    [System.Management.Automation.PSCredential]
    $Credential
)

Configuration Custom
{
    param (
        [parameter()]
        [System.Management.Automation.PSCredential]
        $Credential
    )

    if ($null -eq $Credential)
    {
        <# Credentials #>
        $Credscredential = Get-Credential -Message "Credentials"

    }
    else
    {
        $CredsCredential = $Credential
    }

    $OrganizationName = $CredsCredential.UserName.Split('@')[1]

    Import-DscResource -ModuleName 'Microsoft365DSC' -ModuleVersion '1.23.705.1'

    Node localhost
    {
        IntuneSettingCatalogCustomPolicyWindows10 "IntuneSettingCatalogCustomPolicyWindows10-TEST"
        {
            Assignments          = @();
            Credential           = $Credscredential;
            Description          = "Test";
            Ensure               = "Present";
            Id                   = "495a239d-4367-474f-86e8-225d9f6bbe11";
            Name                 = "Setting Catalogue- Block MS Edge Shortcuts";
            Platforms            = "windows10";
            Settings             = @(
                MSFT_MicrosoftGraphdeviceManagementConfigurationSetting{
                    SettingInstance = MSFT_MicrosoftGraphDeviceManagementConfigurationSettingInstance{
                        choiceSettingValue = MSFT_MicrosoftGraphDeviceManagementConfigurationChoiceSettingValue{
                            Value = 'device_vendor_msft_policy_config_updatev83diff~policy~cat_edgeupdate~cat_applications_pol_defaultcreatedesktopshortcut_0'
                        }
                        SettingDefinitionId = 'device_vendor_msft_policy_config_updatev83diff~policy~cat_edgeupdate~cat_applications_pol_defaultcreatedesktopshortcut'
                        odataType = '#microsoft.graph.deviceManagementConfigurationChoiceSettingInstance'
                    }
                }
            );
            Technologies         = "mdm";
        }
    }
}

Custom -ConfigurationData .\ConfigurationData.psd1 -Credential $Credential

ConvertTo-DscObject is missing to define CIMInstance in nested properties

On resources with deeply nested properties such as IntuneDeviceConfigurationAdministrativeTemplatePolicyWindows10 some of them miss the CIMInstance property and therefore cannot be identified of which type they belong to. See below the values of the resource after ConvertTo-DscObject, at the bottom you may find the whole blueprint.

PS C:\> $Resource

Name                           Value                                                                                                                                                                        
----                           -----                                                                                                                                                                        
Ensure                         Present                                                                                                                                                                      
Description                                                                                                                                                                                                 
Id                             REDACTED                                                                                                                                         
ResourceName                   IntuneDeviceConfigurationAdministrativeTemplatePolicyWindows10                                                                                                               
Assignments                    {System.Collections.Specialized.OrderedDictionary, System.Collections.Specialized.OrderedDictionary}                                                                         
ResourceInstanceName           IntuneDeviceConfigurationAdministrativeTemplatePolicyWindows10-REDACTED                                                         
PolicyConfigurationIngestio... unknown                                                                                                                                                                      
DefinitionValues               {System.Collections.Specialized.OrderedDictionary, System.Collections.Specialized.OrderedDictionary, System.Collections.Specialized.OrderedDictionary, System.Collections....
DisplayName                    REDACTED

PS C:\> $Resource.DefinitionValues[0]

Name                           Value                                                                                                                                                                        
----                           -----                                                                                                                                                                        
CIMInstance                    MSFT_IntuneGroupPolicyDefinitionValue                                                                                                                                        
ConfigurationType              policy                                                                                                                                                                       
Id                             REDACTED                                                                                                                                         
Definition                     {Id, DisplayName, CategoryPath, PolicyType...}                                                                                                                               
Enabled                        True

PS C:\> $Resource.DefinitionValues[0].Definition

Name                           Value                                                                                                                                                                        
----                           -----                                                                                                                                                                        
Id                             REDACTED                                                                                                                                         
DisplayName                    Silently sign in users to the OneDrive sync app with their Windows credentials                                                                                               
CategoryPath                   \OneDrive                                                                                                                                                                    
PolicyType                     admxIngested                                                                                                                                                                 
SupportedOn                    At least Windows Server 2008 R2 or Windows 7                                                                                                                                 
ClassType                      machine

The last object is missing a CIMInstance property with value "MSFT_IntuneGroupPolicyDefinitionValueDefinition" like this:

PS C:\> $Resource.DefinitionValues[0].Definition

Name                           Value
----                           -----
CIMInstance                    MSFT_IntuneGroupPolicyDefinitionValueDefinition
Id                             REDACTED                                                                                                                                         
DisplayName                    Silently sign in users to the OneDrive sync app with their Windows credentials                                                                                               
CategoryPath                   \OneDrive                                                                                                                                                                    
PolicyType                     admxIngested                                                                                                                                                                 
SupportedOn                    At least Windows Server 2008 R2 or Windows 7                                                                                                                                 
ClassType                      machine
param (
    [parameter()]
    [System.Management.Automation.PSCredential]
    $Credential
)

Configuration ConfigureMicrosoft365
{
    param (
        [parameter()]
        [System.Management.Automation.PSCredential]
        $Credential
    )

    if ($null -eq $Credential)
    {
        <# Credentials #>
        $Credscredential = Get-Credential -Message "Credentials"

    }
    else
    {
        $CredsCredential = $Credential
    }

    $OrganizationName = $CredsCredential.UserName.Split('@')[1]

    Import-DscResource -ModuleName 'Microsoft365DSC'

    Node localhost
    {
        IntuneDeviceConfigurationAdministrativeTemplatePolicyWindows10 "IntuneDeviceConfigurationAdministrativeTemplatePolicyWindows10-REDACTED"
        {
            ApplicationId                    = $ConfigurationData.NonNodeData.ApplicationId;
            Assignments                      = @(
                MSFT_DeviceManagementConfigurationPolicyAssignments{
                    deviceAndAppManagementAssignmentFilterType = 'none'
                    dataType = '#microsoft.graph.exclusionGroupAssignmentTarget'
                    groupId = 'REDACTED'
                }
                MSFT_DeviceManagementConfigurationPolicyAssignments{
                    deviceAndAppManagementAssignmentFilterType = 'none'
                    dataType = '#microsoft.graph.groupAssignmentTarget'
                    groupId = 'REDACTED'
                }
            );
            CertificateThumbprint            = $ConfigurationData.NonNodeData.CertificateThumbprint;
            DefinitionValues                 = @(
                MSFT_IntuneGroupPolicyDefinitionValue{
                    ConfigurationType = 'policy'
                    Id = 'REDACTED'
                    Definition = MSFT_IntuneGroupPolicyDefinitionValueDefinition{
                        Id = 'REDACTED'
                        DisplayName = 'Silently sign in users to the OneDrive sync app with their Windows credentials'
                        CategoryPath = '\OneDrive'
                        PolicyType = 'admxIngested'
                        SupportedOn = 'At least Windows Server 2008 R2 or Windows 7'
                        ClassType = 'machine'
                    }
                    Enabled = $True
                }
                MSFT_IntuneGroupPolicyDefinitionValue{
                    ConfigurationType = 'policy'
                    Id = 'REDACTED'
                    Definition = MSFT_IntuneGroupPolicyDefinitionValueDefinition{
                        Id = 'REDACTED'
                        DisplayName = 'Prevent users from syncing libraries and folders shared from other organizations'
                        CategoryPath = '\OneDrive'
                        PolicyType = 'admxIngested'
                        SupportedOn = 'At least Windows Server 2008 R2 or Windows 7'
                        ClassType = 'machine'
                    }
                    Enabled = $True
                }
                MSFT_IntuneGroupPolicyDefinitionValue{
                    ConfigurationType = 'policy'
                    Id = 'REDACTED'
                    Definition = MSFT_IntuneGroupPolicyDefinitionValueDefinition{
                        Id = 'REDACTED'
                        DisplayName = 'Require users to confirm large delete operations'
                        CategoryPath = '\OneDrive'
                        PolicyType = 'admxIngested'
                        SupportedOn = 'At least Windows Server 2008 R2 or Windows 7'
                        ClassType = 'machine'
                    }
                    Enabled = $True
                }
                MSFT_IntuneGroupPolicyDefinitionValue{
                    ConfigurationType = 'policy'
                    Id = 'REDACTED'
                    Definition = MSFT_IntuneGroupPolicyDefinitionValueDefinition{
                        Id = 'REDACTED'
                        DisplayName = 'Use OneDrive Files On-Demand'
                        CategoryPath = '\OneDrive'
                        PolicyType = 'admxIngested'
                        SupportedOn = 'At least Windows Server 2016, Windows 10 Version 1709'
                        ClassType = 'machine'
                    }
                    Enabled = $True
                }
            );
            Description                      = "";
            DisplayName                      = "REDACTED";
            Ensure                           = "Present";
            Id                               = "REDACTED";
            PolicyConfigurationIngestionType = "unknown";
            TenantId                         = $OrganizationName;
        }
    }
}

ConvertTo-DSCObject doesn't handle arrays with multiple cim instance PS objects well

I've objects that look more or less like this:

    Node localhost
    {
        AADConditionalAccessPolicy 706192c4-1a75-465c-9592-479a9e90858e
        {
            ApplicationEnforcedRestrictionsIsEnabled = $False;
            #BuiltInControls                          = @("block");
            BuiltInControls                               = @(
                MSFT_SCLabelSetting
                {
                    Key   = 'contenttype'
                    Value = 'File  Email  Site  UnifiedGroup'
                }
                MSFT_SCLabelSetting
                {
                    Key   = 'tooltip'
                    Value = 'Disclosure of the information has substantial negative impact'
                }
            );
            ClientAppTypes                           = @("exchangeActiveSync","other");
            CloudAppSecurityIsEnabled                = $False;
            CloudAppSecurityType                     = "";
        }
     }

image

While you handle correctly strings, numbers, you overwrite the array if it's CIM instance with hashtable instead of adding it to array.

ConvertTo-DSCObject: Key cannot be null

Today I tried to convert the result of Export-O365Configuration.

param (
    [parameter()]
    [System.Management.Automation.PSCredential]
    $GlobalAdminAccount
)

Configuration O365TenantConfig
{
    param (
        [parameter()]
        [System.Management.Automation.PSCredential]
        $GlobalAdminAccount
    )

    Import-DSCResource -ModuleName Office365DSC

    if ($null -eq $GlobalAdminAccount)
    {
        <# Credentials #>
        $Credsglobaladmin = Get-Credential -Message "Global Admin credentials"
    }
    else
    {
        $Credsglobaladmin = $GlobalAdminAccount
    }

    $OrganizationName = $Credsglobaladmin.UserName.Split('@')[1]
    Node localhost
    {}
}

This results in the following error. The error happens in line 24 for the variable GlobalAdminAccount.

ConvertTo-DSCObject : Key cannot be null.
Parameter name: key
At line:1 char:1
+ ConvertTo-DSCObject .\Modules\Office365QuickStart\TenantConfiguration ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [ConvertTo-DSCObject], ArgumentNullException
    + FullyQualifiedErrorId : System.ArgumentNullException,ConvertTo-DSCObject

The error is a result of line 84:

 $currentProperty = $component.Content.ToString()

as $currentProperty is $null in this iteration.

preserve empty properties

is it possible to preserve empty properties and write them back into the file, because I want to preserve as much information about an object as possible.
I get the following object from M365Dsc Export:
AADGroup "AADGroup-sg-Legal"
{
ApplicationId = $ConfigurationData.NonNodeData.ApplicationId;
CertificateThumbprint = $ConfigurationData.NonNodeData.CertificateThumbprint;
Description = "All legal executives";
DisplayName = "sg-Legal";
Ensure = "Present";
GroupTypes = @();
Id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
MailEnabled = $False;
MailNickname = "sgLegal";
MemberOf = @();
Members = @("[email protected]","[email protected]","[email protected]");
Owners = @();
SecurityEnabled = $True;
TenantId = $OrganizationName;
}

When I use the following code:
$converted=ConvertTo-DSCObject -Path .\M365TenantConfig.ps1
$convertedback = ConvertFrom-DSCObject $converted

after the conversion the object looks like this:
AADGroup "AADGroup-sg-Legal"
{
Description = "All legal executives"
MailEnabled = $False
Id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
ApplicationId = "$ConfigurationData.NonNodeData.ApplicationId"
Ensure = "Present"
MailNickname = "sgLegal"
SecurityEnabled = $True
TenantId = "$OrganizationName"
CertificateThumbprint = "$ConfigurationData.NonNodeData.CertificateThumbprint"
DisplayName = "sg-Legal"
Members = @("[email protected]","[email protected]","[email protected]")
}

Is it possible to add a flag with convertFrom-DSCObject like preserveEmptyProperties so that I also get the empty properties back again after conversion?

ConvertTo-DSCObject not converting correctly a specific property in a blueprint

Given the blueprint at the bottom when converting it to a PSObject a specific property called QuestionText (inside Questions) for some reason is not being converted correctly, whereas every other properties are. Any thoughts on this?

The current output of that property is the following

PS C:\ $Resource.Questions

Name                           Value
----                           -----
CIMInstance                    MSFT_MicrosoftGraphaccesspackagequestion
Sequence                       0
IsRequired                     False
Id                             69e983df-f773-4e0f-ade9-33e83fbfbce2
odataType                      #microsoft.graph.accessPackageTextInputQuestion
IsSingleLineQuestion           True
QuestionText
DefaultText                    Why do you want to be the cool 1234?

Instead it should show the following, including the child property

PS C:\ $Resource.Questions

Name                           Value
----                           -----
CIMInstance                    MSFT_MicrosoftGraphaccesspackagequestion
Sequence                       0
IsRequired                     False
Id                             69e983df-f773-4e0f-ade9-33e83fbfbce2
odataType                      #microsoft.graph.accessPackageTextInputQuestion
IsSingleLineQuestion           True
QuestionText                   {System.Collections.Specialized.OrderedDictionary}

PS C:\ $Resource.Questions.QuestionText

Name                           Value
----                           -----
CIMInstance                    MSFT_MicrosoftGraphaccessPackageLocalizedContent
DefaultText                    Why do you want to be the cool 1234?

And now the blueprint with this issue

Configuration M365TenantConfig
{
    param ()

    $OrganizationName = $ConfigurationData.NonNodeData.OrganizationName

    Import-DscResource -ModuleName 'Microsoft365DSC' -ModuleVersion '1.23.503.1'

    Node localhost
    {
        AADEntitlementManagementAccessPackageAssignmentPolicy "AADEntitlementManagementAccessPackageAssignmentPolicy-Initial Policy"
        {
            AccessPackageId         = "772e529d-f77c-45c8-aec2-62838d940dd1";
            AccessReviewSettings    = MSFT_MicrosoftGraphassignmentreviewsettings{
                IsApprovalJustificationRequired = $True
                ReviewerType = 'Manager'
                IsEnabled = $True
                RecurrenceType = 'quarterly'
                DurationInDays = 25
                StartDateTime = '11/18/2022 22:59:59'
                AccessReviewTimeoutBehavior = 'keepAccess'
                IsAccessRecommendationEnabled = $True
            };
            ApplicationId           = $ConfigurationData.NonNodeData.ApplicationId;
            CanExtend               = $False;
            CertificateThumbprint   = $ConfigurationData.NonNodeData.CertificateThumbprint;
            Description             = "Initial Policy";
            DisplayName             = "Initial Policy";
            DurationInDays          = 0;
            Ensure                  = "Present";
            Id                      = "510fcf5b-9756-4e18-8039-8a606a9f41b5";
            Questions               = @(
                MSFT_MicrosoftGraphaccesspackagequestion{
                    Sequence = 0
                    IsRequired = $False
                    Id = '69e983df-f773-4e0f-ade9-33e83fbfbce2'
                    odataType = '#microsoft.graph.accessPackageTextInputQuestion'
                    IsSingleLineQuestion = $True
                    QuestionText = MSFT_MicrosoftGraphaccessPackageLocalizedContent{
                        DefaultText = 'Why do you want to be the cool 1234?'
                    }
                }
            );
            RequestApprovalSettings = MSFT_MicrosoftGraphapprovalsettings{
                IsRequestorJustificationRequired = $True
                IsApprovalRequired = $True
                ApprovalMode = 'SingleStage'
                ApprovalStages = @(
                    MSFT_MicrosoftGraphapprovalstage1{
                        PrimaryApprovers = @(
                            MSFT_MicrosoftGraphuserset{
                                Id = '8a82928b-486b-4ff6-b652-083fb99104df'
                                odataType = '#microsoft.graph.singleUser'
                                IsBackup = $True
                                ManagerLevel = 1
                            }

                            MSFT_MicrosoftGraphuserset{
                                Id = '6ca2d4f7-0674-4ae0-ad2f-a812f8f8766c'
                                odataType = '#microsoft.graph.requestorManager'
                                IsBackup = $False
                            }
                        )
                        IsEscalationEnabled = $False
                        ApprovalStageTimeOutInDays = 14
                        EscalationTimeInMinutes = 0
                        IsApproverJustificationRequired = $True
                    }
                )
                IsApprovalRequiredForExtension = $False
            };
            RequestorSettings       = MSFT_MicrosoftGraphrequestorsettings{
                AllowedRequestors = @(
                    MSFT_MicrosoftGraphuserset{
                        Id = '331925dc-c11a-4669-9dee-d32882b1d791'
                        odataType = '#microsoft.graph.requestorManager'
                        IsBackup = $true
                    }
                )
                ScopeType = 'SpecificDirectorySubjects'
                AcceptRequests = $True
            };
            TenantId                = $ConfigurationData.NonNodeData.TenantId;
        }
    }
}

M365TenantConfig -ConfigurationData .\ConfigurationData.psd1

ConvertTo-DscObject hangs

Using ConvertTo-DscObject with PS 5.1 hangs due to an infinite loop in the code. I believe the issue results from

while ($parsedData[$newIndexPosition].Type -ne 'Keyword')
as in the while statement $i gets incremented which is also used in the for loop
for ($i = 0; $i -lt $parsedData.Count; $i++)
and thus the for-loop never terminates. Also, there seems to be a change in the actual behavior in PS. It is documented here: #15.

Using the variable name escape syntax causes DSCParser to display wrong object

I was given a new DSC file from one of my colleagues and DSCParser started to show weird properties and values. I've minified the DSC to something that is easily visible on the first object - Basically a value of $ConfigurationData.NonNodeData.ApplicationId; is messing up display

Configuration DSCExport
{
    $OrganizationName = $ConfigurationData.NonNodeData.OrganizationName
    Import-DscResource -ModuleName 'Microsoft365DSC' #-ModuleVersion '1.22.323.1'

    Node localhost
    {
        AADConditionalAccessPolicy 74ec9f84-045a-4e9c-846c-7875667a553a {
            ApplicationId = $ConfigurationData.NonNodeData.ApplicationId;
            DisplayName   = "All - Deny Basic authentication";
        }
        AADConditionalAccessPolicy aead38b8-dcd6-4736-8cec-849321084008
        {
            ApplicationEnforcedRestrictionsIsEnabled = $False;
            ApplicationId                            = $ConfigurationData.NonNodeData.ApplicationId;
            ApplicationSecret                        = $ConfigurationData.NonNodeData.ApplicationSecret;
            BuiltInControls                          = @("mfa");
            ClientAppTypes                           = @("all");
            CloudAppSecurityIsEnabled                = $False;
            CloudAppSecurityType                     = "";
            DisplayName                              = "Guest - Require Azure MFA";
            Ensure                                   = "Present";
            ExcludeApplications                      = @();
            ExcludeDevices                           = @();
            ExcludeGroups                            = @();
            ExcludeLocations                         = @();
            ExcludePlatforms                         = @();
            ExcludeRoles                             = @();
            ExcludeUsers                             = @("Admin@$OrganizationName");
            GrantControlOperator                     = "OR";
            Id                                       = "d5041603-f45d-456e-a0ac-eb9bae39c785";
            IncludeApplications                      = @("All");
            IncludeDevices                           = @();
            IncludeGroups                            = @();
            IncludeLocations                         = @();
            IncludePlatforms                         = @();
            IncludeRoles                             = @();
            IncludeUserActions                       = @();
            IncludeUsers                             = @("GuestsOrExternalUsers");
            PersistentBrowserIsEnabled               = $False;
            PersistentBrowserMode                    = "";
            SignInFrequencyIsEnabled                 = $False;
            SignInFrequencyType                      = "";
            SignInRiskLevels                         = @();
            State                                    = "enabled";
            TenantId                                 = $ConfigurationData.NonNodeData.TenantId;
            UserRiskLevels                           = @();
        }
        SCLabelPolicy 99ef4d19-e250-4009-9a4e-70659fe2a34a {
            # This should be comment
            AdvancedSettings = @(
                # This should be comment
                MSFT_SCLabelSetting {
                    Key   = 'requiredowngradejustification'
                    Value = $null
                }
                MSFT_SCLabelSetting {
                    Key   = 'customurl'
                    Value = $true
                }
            );
            Credential       = $Credscredential;
            Ensure           = $true
            ExchangeLocation =$null
            Labels           = @("Confidential", $true, $null, "Eurofins Internal");
            Name             = "Default Label Policy";
        }
    }
}
DSCExport -ConfigurationData .\ConfigurationData.psd1

The first object as created with current DSCParser

image

As you can notice $ConfigurationData variable completely gone, NonNodeData part of variable becomes property and rest of variable is put as a value. Not great, a bit unreadable and confusing.

It gets messier if there are more variables like that:

image

DSCParser 1.3.0.3 is working on one machine, and isn't working on another

Hello!
Running the same script on 2 machines, on 1st PC it is working normally, on the second isn't.
Could you please tell me what is the dependency?
1st machine:

Name                           Value
----                           -----
PSVersion                      5.1.19041.1320
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.1320
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

2st:

Name                           Value
----                           -----
PSVersion                      5.1.19041.1320
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.1320
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

As you can see, the PS Version is the same.
I'm getting the DSC using this script block:

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $AzureDevOpsPAT )))
    $RequestURl = "https://dev.azure.com/$OrganizationName/$ProjectName/_apis/git/repositories/$RepoName/items?path=$RepoFilePath&download=true&api-version=5.0"
    $Headers = @{Authorization = ("Basic {0}" -f $base64AuthInfo) }

    Write-Verbose "Trying to get the file from ADO"
    try {
        $RequestSplat = @{
            Uri         = $RequestURl
            Method      = "GET"
            ContentType = "application/text"
            Headers     = $Headers
            ErrorAction = "STOP"
        }

        $BlueprintContent = Invoke-RestMethod @RequestSplat
        $BlueprintParsedObject = ConvertTo-DSCObject -Content $BlueprintContent
        Write-Verbose "File has been downloaded successfully"
        return $BlueprintParsedObject
    }
    catch {
        Write-Error $_.Exception | Select-object *
        break
    }

On the first machine it returns DSC object, on the second returns nothing

Downloaded files also can't be parsed on the second PC

ConvertTo-DSCObject does not work in Powershell 7.1.1

ConvertTo-DSCObject hangs on endless loop on Powershell 7.1.1

ConvertTo-DSCObject, from line 81 :

      elseif ($parsedData[$i].Content -eq 'node')
        {
            $nodeKeyWordEncountered = $true
            $newIndexPosition = $i+1
            while ($parsedData[$newIndexPosition].Type -ne 'Keyword')
            {
                $i++
                $newIndexPosition = $i+1
            }
        }

Loops endlessly because there's no more 'Keyword' tokens

The PSParser in Powershell 7.1.1 gives different tokentypes for some tokens.
(not sure if this is a bug or intentionally, PowerShell/PowerShell#13779 is the only change i found involving the parser in recent releases)

the DSC Resource on this page : http://nikcharlebois.com/cloud-lcm-prototype-for-dsc-as-a-service/ gives these token types (just listed the ones that are different in pre-7.1.1 and 7.1.1)

Content Type (< 7.1.1) Type (7.1.1) Start
AADMSGroupLifecyclePolicy Keyword Command 809
aa1d0235-e1aa-4c52-a496-f96c81f7d2f4 Command CommandArgument 835
IsSingleInstance Member Command 896
= Operator CommandArgument 924
GroupLifetimeInDays Member Command 946
= Operator CommandArgument 974
ManagedGroupTypes Member Command 993
= Operator CommandArgument 1021
AlternateNotificationEmails Member Command 1042
= Operator CommandArgument 1070
Ensure Member Command 1116
= Operator CommandArgument 1144
GlobalAdminAccount Member Command 1170
= Operator CommandArgument 1198
AADGroupsNamingPolicy Keyword Command 1239
CustomBlockedWordsList Member Command 1304
= Operator CommandArgument 1334
GlobalAdminAccount Member Command 1372
= Operator CommandArgument 1402
IsSingleInstance Member Command 1436
= Operator CommandArgument 1466
PrefixSuffixNamingRequirement Member Command 1488
= Operator CommandArgument 1518

Again not sure if it should be fixed here...
But it should atleast throw an error if $i becomes larger than $parsedData.Count to prevent an endless loop

Split into multiple files and add tests

I was wondering if we can split this project into multiple files and add tests:

  • It would be easier to manage
  • It would be easier to change things and make sure we don't break existing functionality

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.