Giter Site home page Giter Site logo

dsccommunity / filecontentdsc Goto Github PK

View Code? Open in Web Editor NEW
14.0 14.0 4.0 299 KB

DSC resources for setting the content of files. Configuration text files are the most common use case for this module.

Home Page: https://dsccommunity.org

License: MIT License

PowerShell 100.00%
dsc-resources file-content ini-settings-file key-value-pair-file powershell-dsc replace-text

filecontentdsc's People

Contributors

dscottraynsford avatar jcwalker avatar johlju avatar nehrua avatar plagueho avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar

filecontentdsc's Issues

Set Optional Failure Flags for all PSSA Tests

Add the following opt-in settings to enable CI failure on violation of these PSSA rule types:

  • Common Tests - Required Script Analyzer Rules
  • Common Tests - Flagged Script Analyzer Rules
  • Common Tests - New Error-Level Script Analyzer Rules
  • Common Tests - Custom Script Analyzer Rules

ReplaceText: Exception calling "Matches" error when text file is blank/empty

Details of the scenario you tried and the problem that is occurring

When using the ReplaceText DSC resource in order to Append Text to a blank/empty text file, the resource throws an error "Exception calling "Matches" with "2" argument(s): "Value cannot be null. Parameter name: input"

Verbose logs showing the problem

image

Suggested solution to the issue

Enable the resource to handle blank/empty file scenarios. The issue occurs due to $fileContent having a null value, which is expected when the file is blank.

The DSC configuration that is used to reproduce the issue (as detailed as possible)

configuration BlankFileScenario
{
    Import-DscResource -ModuleName FileContentDsc

    node localhost
    {
        ReplaceText "BlankEmpty File"
        {
            Path        = 'C:\Dev\blankFile.txt' #blank file -> Get-Content should be true when compared to $null
            Search      = 'search'
            Type        = 'Text'
            Text        = 'replacement'
            AllowAppend = $true
        }
    }
}

The operating system the target node is running

Windows Server 2012 R2

Version and build of PowerShell the target node is running

5.1.14409.1018

Version of the DSC module that was used ('dev' if using current dev branch)

1.1.0.108

Update GitVersion.yml to use latest pattern

Update GitVersion.yml branches section to:

branches:
  master:
    tag: preview
    regex: ^main$
  pull-request:
    tag: PR
  feature:
    tag: useBranchName
    increment: Minor
    regex: f(eature(s)?)?[\/-]
    source-branches: ['master']
  hotfix:
    tag: fix
    increment: Patch
    regex: (hot)?fix(es)?[\/-]
    source-branches: ['master']

As per: dsccommunity/dsccommunity.org#162

KeyValuePairFile: Unable to insert into empty file.

Details of the scenario you tried and the problem that is occurring

Hi, I was trying to run KeyValuePairFile from FileContentDsc on an empty .config file to try to populate some new entries. Not sure if this is supported or not or if I should be using a different DSC resource, but I kept getting errors, I'm assuming because the file was empty and everything the DSC resource was trying to work with was null.

Realistically, for what I'm going to be using this for, I won't be having this issue. Just figured I'd bring it up since I ran into it.

Verbose logs showing the problem

This was in my event viewer for operational DSC logs:

Event 4252 -
Job {43432191-A78D-11E9-837E-408D5C58C088} :
MIResult: 1
Error Message: Exception calling "Matches" with "3" argument(s): "Value cannot be null.
Parameter name: input"
Message ID: ArgumentNullException
Error Category: 0
Error Code: 1
Error Type: MI

From Get-DscConfigurationStatus -

Get-DscConfigurationStatus | select -ExpandProperty ResourcesnotInDesiredState


ConfigurationName    : splunkServerConfconfig
DependsOn            :
ModuleName           : FileContentDsc
ModuleVersion        : 1.1.0.108
PsDscRunAsCredential :
ResourceId           : [KeyValuePairFile]splunkServerConf_serverCert
SourceInfo           : ::15::9::KeyValuePairFile
DurationInSeconds    : 0.067
Error                : {
                           "Exception":  {
                                             "Message":  "The PowerShell DSC resource \u0027[KeyValuePairFile]splunkServerConf_serverCert\u0027 with SourceInfo \u0027::15::9::KeyValuePairFile\u0027 threw one or more non-terminating
                       errors while running the Test-TargetResource functionality. These errors are logged to the ETW channel called Microsoft-Windows-DSC/Operational. Refer to this channel for more details.",
                                             "Data":  {

                                                      },
                                             "InnerException":  null,
                                             "TargetSite":  null,
                                             "StackTrace":  null,
                                             "HelpLink":  null,
                                             "Source":  null,
                                             "HResult":  -2146233079
                                         },
                           "TargetObject":  null,
                           "CategoryInfo":  {
                                                "Category":  7,
                                                "Activity":  "",
                                                "Reason":  "InvalidOperationException",
                                                "TargetName":  "",
                                                "TargetType":  ""
                                            },
                           "FullyQualifiedErrorId":  "NonTerminatingErrorFromProvider",
                           "ErrorDetails":  null,
                           "InvocationInfo":  null,
                           "ScriptStackTrace":  null,
                           "PipelineIterationInfo":  [

                                                     ]
                       }
FinalState           :
InDesiredState       : False
InitialState         :
InstanceName         : splunkServerConf_serverCert
RebootRequested      : False
ResourceName         : KeyValuePairFile
StartDate            : 7/15/2019 11:01:41 PM
StateChanged         : False
PSComputerName       :


ConfigurationName    : splunkServerConfconfig
DependsOn            :
ModuleName           : FileContentDsc
ModuleVersion        : 1.1.0.108
PsDscRunAsCredential :
ResourceId           : [KeyValuePairFile]splunkServerConf_sslPassword
SourceInfo           : ::24::9::KeyValuePairFile
DurationInSeconds    : 0.01
Error                : {
                           "Exception":  {
                                             "Message":  "The PowerShell DSC resource \u0027[KeyValuePairFile]splunkServerConf_sslPassword\u0027 with SourceInfo \u0027::24::9::KeyValuePairFile\u0027 threw one or more non-terminating
                       errors while running the Test-TargetResource functionality. These errors are logged to the ETW channel called Microsoft-Windows-DSC/Operational. Refer to this channel for more details.",
                                             "Data":  {

                                                      },
                                             "InnerException":  null,
                                             "TargetSite":  null,
                                             "StackTrace":  null,
                                             "HelpLink":  null,
                                             "Source":  null,
                                             "HResult":  -2146233079
                                         },
                           "TargetObject":  null,
                           "CategoryInfo":  {
                                                "Category":  7,
                                                "Activity":  "",
                                                "Reason":  "InvalidOperationException",
                                                "TargetName":  "",
                                                "TargetType":  ""
                                            },
                           "FullyQualifiedErrorId":  "NonTerminatingErrorFromProvider",
                           "ErrorDetails":  null,
                           "InvocationInfo":  null,
                           "ScriptStackTrace":  null,
                           "PipelineIterationInfo":  [

                                                     ]
                       }
FinalState           :
InDesiredState       : False
InitialState         :
InstanceName         : splunkServerConf_sslPassword
RebootRequested      : False
ResourceName         : KeyValuePairFile
StartDate            : 7/15/2019 11:01:41 PM
StateChanged         : False
PSComputerName       :

The DSC configuration that is used to reproduce the issue (as detailed as possible)

Configuration splunkServerConfconfig 
{
    
    [Cmdletbinding()]
    param
    (
        [parameter()]
        [string[]]
        $NodeName = 'localhost'
    )
    Import-DscResource -ModuleName FileContentDsc

    Node $NodeName
    {
        KeyValuePairFile splunkServerConf_serverCert
        {
            Path = "B:\Code\GitHub\PowerShell\SplunkDSCTest\server.conf"
            Name = "serverCert"
            Text = "B:\fakecert.pem"
            Type = "Text"
            Ensure = "Present"
        }
        
        KeyValuePairFile splunkServerConf_sslPassword
        {
            Path = "B:\Code\GitHub\PowerShell\SplunkDSCTest\server.conf"
            Name = "sslPassword"
            Text = "passwordpassword"
            Type = "Text"
            Ensure = "Present"
        }
    }
}

Version and build of PowerShell the target node is running

Name Value


PSVersion 5.1.17763.592
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17763.592
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1

Version of the DSC module that was used ('dev' if using current dev branch)

1.1.0.108

KeyValuePairFile: Key Value Pair not removed when 'Ensure' marked as 'Absent'

Problem description

When attempting to remove a Key/Value pair from a file, the Key/Value pair is not removed

Verbose logs

Perform operation 'Invoke CimMethod' with following parameters, ''methodName' = 
PerformRequiredConfigurationChecks,'className' = MSFT_DSCLocalConfigurationManager,'namespaceName' = 
root/Microsoft/Windows/DesiredStateConfiguration'.
An LCM method call arrived from computer SERVER1 with user sid {SID}.
[SERVER1]:                            [] Executing Get-Action with configuration (null)'s checksum: 
5650263B30602B97769572C32951366FD4A3A2DA0AE1886205F3F1E73E727F3E.
[SERVER1]:                            [] Executing Get-Action with configuration 's checksum returned result 
status: GetConfiguration.
[SERVER1]:                            [] Checksum is different. LCM will execute GetConfiguration to pull 
configuration .
[SERVER1]:                            [] Executing GetConfiguration succeeded. Configuration  was pulled from 
server.
[SERVER1]:                            [] Applying the new configuration(s) pulled.
[SERVER1]: LCM:  [ Start  Resource ]  [[MsiPackage]InstallZabbix609]
[SERVER1]: LCM:  [ Start  Test     ]  [[MsiPackage]InstallZabbix609]
[SERVER1]:                            [[MsiPackage]InstallZabbix609] Parsing 
{020E0A73-C192-4D8C-AF6A-7986F7D26F69} as an identifyingNumber
[SERVER1]:                            [[MsiPackage]InstallZabbix609] Parsed 
{020E0A73-C192-4D8C-AF6A-7986F7D26F69} as {020E0A73-C192-4D8C-AF6A-7986F7D26F69}
[SERVER1]:                            [[MsiPackage]InstallZabbix609] The package Zabbix Agent 2 (64-bit) is 
installed
[SERVER1]: LCM:  [ End    Test     ]  [[MsiPackage]InstallZabbix609]  in 0.0470 seconds.
[SERVER1]: LCM:  [ Skip   Set      ]  [[MsiPackage]InstallZabbix609]
[SERVER1]: LCM:  [ End    Resource ]  [[MsiPackage]InstallZabbix609]
[SERVER1]: LCM:  [ Start  Resource ]  [[KeyValuePairFile]ZabbixHostnameRemoved]
[SERVER1]: LCM:  [ Start  Test     ]  [[KeyValuePairFile]ZabbixHostnameRemoved]
[SERVER1]:                            [[KeyValuePairFile]ZabbixHostnameRemoved] Searching for key 'Hostname' in 
file 'C:\Program Files\Zabbix Agent 2\zabbix_agent2.conf'.
[SERVER1]:                            [[KeyValuePairFile]ZabbixHostnameRemoved] Key 'Hostname' not found in file 
'C:\Program Files\Zabbix Agent 2\zabbix_agent2.conf' and should not exist. Change not required.
[SERVER1]:                            [[KeyValuePairFile]ZabbixHostnameRemoved] File encoding is set to 'UTF8' 
but should be set to 'ASCII', Change required.
[SERVER1]: LCM:  [ End    Test     ]  [[KeyValuePairFile]ZabbixHostnameRemoved]  in 0.0940 seconds.
[SERVER1]: LCM:  [ Start  Set      ]  [[KeyValuePairFile]ZabbixHostnameRemoved]
[SERVER1]:                            [[KeyValuePairFile]ZabbixHostnameRemoved] Searching for key 'Hostname' in 
file 'C:\Program Files\Zabbix Agent 2\zabbix_agent2.conf'.
[SERVER1]:                            [[KeyValuePairFile]ZabbixHostnameRemoved] File encoding is set to 'UTF8' 
but should be set to 'ASCII', Change required.
[SERVER1]: LCM:  [ End    Set      ]  [[KeyValuePairFile]ZabbixHostnameRemoved]  in 0.3860 seconds.
[SERVER1]: LCM:  [ End    Resource ]  [[KeyValuePairFile]ZabbixHostnameRemoved]
[SERVER1]: LCM:  [ Start  Resource ]  [[KeyValuePairFile]ZabbixHostnameItem]
[SERVER1]: LCM:  [ Start  Test     ]  [[KeyValuePairFile]ZabbixHostnameItem]
[SERVER1]:                            [[KeyValuePairFile]ZabbixHostnameItem] Searching for key 'HostnameItem' in 
file 'C:\Program Files\Zabbix Agent 2\zabbix_agent2.conf'.
[SERVER1]:                            [[KeyValuePairFile]ZabbixHostnameItem] Key 'HostnameItem' found in file 
'C:\Program Files\Zabbix Agent 2\zabbix_agent2.conf' and should exist and value(s) are correct. Change not required.
[SERVER1]: LCM:  [ End    Test     ]  [[KeyValuePairFile]ZabbixHostnameItem]  in 0.0310 seconds.
[SERVER1]: LCM:  [ Skip   Set      ]  [[KeyValuePairFile]ZabbixHostnameItem]
[SERVER1]: LCM:  [ End    Resource ]  [[KeyValuePairFile]ZabbixHostnameItem]
[SERVER1]: LCM:  [ Start  Resource ]  [[Service]ZabbixAgentIsRunning]
[SERVER1]: LCM:  [ Start  Test     ]  [[Service]ZabbixAgentIsRunning]
[SERVER1]:                            [[Service]ZabbixAgentIsRunning] Service Zabbix Agent 2 exists.
[SERVER1]:                            [[Service]ZabbixAgentIsRunning] Perform operation 'Query CimInstances' 
with following parameters, ''queryExpression' = SELECT * FROM Win32_Service WHERE Name='Zabbix Agent 2','queryDialect' 
= WQL,'namespaceName' = root\cimv2'.
[SERVER1]:                            [[Service]ZabbixAgentIsRunning] Operation 'Query CimInstances' complete.
[SERVER1]:                            [[Service]ZabbixAgentIsRunning] Service Zabbix Agent 2 exists.
[SERVER1]: LCM:  [ End    Test     ]  [[Service]ZabbixAgentIsRunning]  in 0.4530 seconds.
[SERVER1]: LCM:  [ Skip   Set      ]  [[Service]ZabbixAgentIsRunning]
[SERVER1]: LCM:  [ End    Resource ]  [[Service]ZabbixAgentIsRunning]
Operation 'Invoke CimMethod' complete.
Time taken for configuration job to complete is 44.289 seconds

DSC configuration

$MyConfig = @{
    AllNodes = @(
        @{
            NodeName = 'localhost'
        }
        @{
            NodeName    = '*'
            ZabbixProxy = '{IP1},{IP2}'
        }
    )
}

Configuration ZabbixSiteServers {
    Import-DscResource -ModuleName @{ModuleName = 'PSDscResources'; RequiredVersion = '2.12.0.0' } -Name MsiPackage, Service
    Import-DscResource -ModuleName @{ModuleName = 'FileContentDsc'; RequiredVersion = '1.3.0.151' }

    Node $AllNodes.NodeName {
        KeyValuePairFile ZabbixHostnameRemoved
        {
            Path      = 'C:\Program Files\Zabbix Agent 2\zabbix_agent2.conf'
            Name      = 'Hostname'
            Ensure    = 'Absent'
            Text      = [System.String]::Empty
            Encoding  = 'ASCII'
            DependsOn = '[MsiPackage]InstallZabbix609'
        }

        KeyValuePairFile ZabbixHostnameItem
        {
            Path      = 'C:\Program Files\Zabbix Agent 2\zabbix_agent2.conf'
            Name      = 'HostnameItem'
            Ensure    = 'Present'
            Text      = 'system.hostname[netbios,lower]'
            Encoding  = 'ASCII'
            DependsOn = '[MsiPackage]InstallZabbix609'
        }

        MsiPackage InstallZabbix609
        {
            ProductId     = '{020E0A73-C192-4D8C-AF6A-7986F7D26F69}'
            Path          = 'https://cdn.zabbix.com/zabbix/binaries/stable/6.0/6.0.9/zabbix_agent2-6.0.9-windows-amd64-openssl.msi'
            Ensure        = 'Present'
            FileHash      = '15C47E560F8D070F69A0BBFD390280D1B80EAD5775FB202F3A09DADC5A67C91F'
            HashAlgorithm = 'Sha256'
            Arguments     = "ENABLEPATH=1 HOSTMETADATAITEM=system.uname SERVER=""$($Node.ZabbixProxy)"" SERVERACTIVE=""$($Node.ZabbixProxy)"""
        }

        Service ZabbixAgentIsRunning
        {
            Name        = 'Zabbix Agent 2'
            State       = 'Running'
            StartupType = 'Automatic'
            Ensure      = 'Present'
            DependsOn   = '[KeyValuePairFile]ZabbixHostnameItem', '[KeyValuePairFile]ZabbixHostnameRemoved'
        }
    }
}

Suggested solution

The Regex is searching for an EOL Character that doesn't exist.

On line 264 of DSC_KeyValuePairFile.psm1, the regex is requiring $eolChars to exist. This is in contrast to line 242, which is looking for 0 or more matches to $eolChars.

On line 264, change:

$fileContent = [regex]::Replace($fileContent, "^[\s]*$Name=(.*)$eolChars", '', $regExOptions)

to:

$fileContent = [regex]::Replace($fileContent, "^[\s]*$Name=(.*)($eolChars*)", '', $regExOptions)

Operating system the target node is running

OsName               : Microsoft Windows Server 2016 Standard
OsOperatingSystemSKU : StandardServerEdition
OsArchitecture       : 64-bit
WindowsBuildLabEx    : 14393.5501.amd64fre.rs1_release.221103-1703
OsLanguage           : en-US
OsMuiLanguages       : {en-US}

PowerShell version and build the target node is running

5.1.14393.5127

FileContentDsc version

Name           Version   Path
----           -------   ----
FileContentDsc 1.3.0.151 C:\Program Files\WindowsPowerShell\Modules\FileContentDsc\1.3.0.151\FileContentDsc.psd1

Please add support for JSON files

Problem description

Please update FileContentDSC - to include .json find and replace, currently it handles .ini, .txt, and .conf

Verbose logs

n/a

DSC configuration

n/a

Suggested solution

n/a

Operating system the target node is running

n/a

PowerShell version and build the target node is running

n/a

FileContentDsc version

n/a

A fileContent resource for simple file contents

Hi,

The 'file' resource of PSDesiredStateConfiguration lake the ability to create file in different encodings (ascii, utf8 without bom etc...). I haven't find any DSC resource that propose to create files in ASCII, so I planned to write a new one to just create a file with the specified content and selected encoding.

As the fileContent resource is already here and propose similar functionalities, would-you mind if I create a PR with a new 'fileContent' resource for simple files ?

Add Ability to Set Multiple Values at Once

From PowerShellGallery comment:

This Package is great. It sure would be nice if the Search, Type, Text, and Secret parameters were arrays so you could make multiple changes in the same file with one go.

LineInFile: New resource proposal

Description

Many file formats do not match the pre-made assumptions of this module. E.g. the KeyValuePairFile resource almost matches my current requirement, however in my case the key and value should be separated by a colon, not an equal sign. This resource would be more general as it would allow the user to specify the line contents (Text) and a regex to determine whether the line is already present. The proposal is modeled after the lineinfile module in Ansible, however in a simplified form. More options (like InsertBefore, InsertAfter, FirstMatch, Backrefs, Backup, etc) could be added if deemed necessary.

Proposed properties

  • Path: The file to modify.
  • Create: Whether the file should be created if not present (if Ensure = 'Present').
  • Text: The line to insert (if Ensure = 'Present')
  • Regex: The regular expression to find the line to modify. If Ensure = 'Present' the regular expression should match the state before and after modification to ensure idempotence. If Ensure = 'Absent' it will be used to determine whether the line needs to be removed. Only the last found instance will be modified.

Special considerations or limitations

None that I could see.

Fix Build Failures due to Pester 5.x

Pester 5.x has been released and both Sampler and DSCResource.Test has been updated to support it, however, Code Coverage support is not available. To solve this, pin Pester to 4.10.1.

Add ability to specify whether UTF8 files have a BOM or not

Description

There are two types of UTF-8 text files, those with BOM and those without, and both are correct UTF-8.
Unfortunately, on some systems, the presence or absence of the BOM can have a serious impact on the behavior, so it must be handled strictly.

There is no way to specify this in the current implementation of FileContentDsc, and even worse, it behaves differently depending on the PowerShell version running the resource.
(In v5.1 and earlier, the BOM is attached, but in v6 and later, it is not.)

Proposed properties

I suggest adding "UTF8BOM" and "UTF8NoBOM" to the acceptable values for Encoding parameter.

Special considerations or limitations

It would be better not to change the existing "UTF8" behavior to avoid serious breaking changes.

This change will only affects the KeyValuePairFile and ReplaceText, not the IniSettingsFile. This is because it does not have an Encoding parameter.

Unable to use Powershell code containing the $ sign as value for the Text key of the KeyValuePairFile resource

Problem description

Hello,

I want to modify a .conf file using the KeyValuePairFile resource.
The key UserParameter in the .conf file should be the following powershell command:

Get-ChildItem -Recurse CERT:LocalMachine/My | ? { $_.NotAfter -lt (Get-Date).AddMonths(2) } | % { $s=$_.Subject -replace "CN=",""; $e=$_.NotAfter.ToString(); $l=$s+"|"+$e; write-output $l }

However, the resource fails to handle the $ sign, and the result is not as desired.

Expected result:
UserParameter=Get-ChildItem -Recurse CERT:LocalMachine/My | ? { $_.NotAfter -lt (Get-Date).AddMonths(2) } | % { $s=$_.Subject -replace "CN=",""; $e=$_.NotAfter.ToString(); $l=$s+"|"+$e; write-output $l }

Current result with the resource:
UserParameter=Get-ChildItem -Recurse CERT:LocalMachine/My | ? { # This is a configuration file for Zabbix agent 2 (Windows)...

I have the impression that as soon as the resource meets the $ sign, it replaces it with the content of the file.

Thank you.

Verbose logs

VERBOSE: [SRV]: LCM:  [ Start  Test     ]  [[KeyValuePairFile]ZabbixConf]
VERBOSE: [SRV]:                            [[KeyValuePairFile]ZabbixConf] Searching for key 'UserParameter' in file 'C:\Temp\zab.conf'.
VERBOSE: [SRV]: LCM:  [ End    Test     ]  [[KeyValuePairFile]ZabbixConf]  in 0.0490 seconds.
VERBOSE: [SRV]: LCM:  [ Start  Set      ]  [[KeyValuePairFile]ZabbixConf]
VERBOSE: [SRV]:                            [[KeyValuePairFile]ZabbixConf] Searching for key 'UserParameter' in file 'C:\Temp\zab.conf'.
VERBOSE: [SRV]:                            [[KeyValuePairFile]ZabbixConf] Key 'UserParameter' found in file 'C:\Temp\zab.conf' and has been updated.
VERBOSE: [SRV]: LCM:  [ End    Set      ]  [[KeyValuePairFile]ZabbixConf]  in 0.0780 seconds.
VERBOSE: [SRV]: LCM:  [ End    Resource ]  [[KeyValuePairFile]ZabbixConf]

DSC configuration

Configuration ZabbixConf{

    Import-DscResource -ModuleName PSDesiredStateConfiguration
    Import-DscResource -ModuleName FileContentDsc -moduleversion 2.0.0
   
    Node SRV {
        KeyValuePairFile ZabbAgent {
            Path = 'C:\Temp\zab.conf'
            Name = 'UserParameter'
            Ensure = 'Present'            
            Text = 'Get-ChildItem -Recurse CERT:LocalMachine/My | ? { $_.NotAfter -lt (Get-Date).AddMonths(2) } | % { $s=$_.Subject -replace "CN=",""; $e=$_.NotAfter.ToString(); $l=$s+"|"+$e; write-output $l }'
        }
    }
}

Suggested solution

No :(

Operating system the target node is running

OsName               : Microsoft Windows 10 Enterprise        
OsOperatingSystemSKU : EnterpriseEdition                      
OsArchitecture       : 64-bit                                 
WindowsVersion       : 2009                                   
WindowsBuildLabEx    : 19041.1.amd64fre.vb_release.191206-1406
OsLanguage           : en-US                                  
OsMuiLanguages       : {en-US}

PowerShell version and build the target node is running

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

FileContentDsc version

Name           Version   Path
----           -------   ----
FileContentDsc 2.0.0     <C:\Program Files\WindowsPowerShell\Modules\FileContentDsc\2.0.0\FileContentDsc.psd1>

Update CI Pipeline Files from Latest Pattern

Copy the latest patterns for the build.yml, build.ps1 and azure-pipelines.yml from the PR:
dsccommunity/ExchangeDsc#471

build.yml

####################################################
#      DscResource.DocGenerator Configuration      #
####################################################
DscResource.DocGenerator:
  Generate_Conceptual_Help:
    MarkdownCodeRegularExpression:
      - '\`(.+?)\`' # Match inline code-block
      - '\\(\\)' # Match escaped backslash
      - '\[[^\[]+\]\((.+?)\)' # Match markdown URL
      - '_(.+?)_' # Match Italic (underscore)
      - '\*\*(.+?)\*\*' # Match bold
      - '\*(.+?)\*' # Match Italic (asterisk)
  publish:
    - publish_module_to_gallery
    - Publish_Release_To_GitHub
    - Publish_GitHub_Wiki_Content
    - Create_ChangeLog_GitHub_PR
  • Also add updated issue templates and related files:
  • .github\ISSUE_TEMPLATE
  • .github\CONTRIBUTING.md
  • .github\PULL_REQUEST_TEMPLATE.md
  • .github\ISSUE_TEMPLATE\General.md
  • .github\ISSUE_TEMPLATE\Problem_with_resource.yml
  • .github\ISSUE_TEMPLATE\Resource_proposal.yml
  • .github\ISSUE_TEMPLATE\config.yml

Add SECURITY.md as well.

Also, update GitVersion task.

ReplaceText will return TRUE when the string to replace doesn't exist but should

Details of the scenario you tried and the problem that is occurring

When attempting to update a configuration file with an entry and that entry doesn't exist yet
Test-TargetResource returns TRUE. The resource is written in a way that it can only update an entry
in a file if it exists. I think it would be more useful if the resource could add entries to a configuration
file as well.

Verbose logs showing the problem

VERBOSE: Perform operation 'Invoke CimMethod' with following parameters, ''methodName' = SendConfigurationApply,'className' = MSFT_DSCLocalConfigurationManager,'namespaceName' = root/Microsoft/Windows/Desi
redStateConfiguration'.
VERBOSE: An LCM method call arrived from computer 2016-BUILD-1 with user sid S-1-5-21-828028386-903968607-3399198716-500.
VERBOSE: [2016-BUILD-1]: LCM: [ Start Set ]
VERBOSE: [2016-BUILD-1]: [DSCEngine] Importing the module C:\Program Files\WindowsPowerShell\Modules\FileContentDsc\1.0.0.38\DscResources\DSR_ReplaceText\DSR_ReplaceText.psm1 in
force mode.
VERBOSE: [2016-BUILD-1]: LCM: [ Start Resource ] [[ReplaceText]SetTextWithRegex]
VERBOSE: [2016-BUILD-1]: LCM: [ Start Test ] [[ReplaceText]SetTextWithRegex]
VERBOSE: [2016-BUILD-1]: [[ReplaceText]SetTextWithRegex] Importing the module DSR_ReplaceText in force mode.
VERBOSE: [2016-BUILD-1]: [[ReplaceText]SetTextWithRegex] Searching using RegEx 'lockPref("browser.download.dir", ".");' in file 'c:\scratch\firefox.cfg'.
VERBOSE: [2016-BUILD-1]: [[ReplaceText]SetTextWithRegex] String not found using RegEx 'lockPref("browser.download.dir", ".
");' in file 'c:\scratch\firefox.cfg', change not req
uired.
VERBOSE: [2016-BUILD-1]: LCM: [ End Test ] [[ReplaceText]SetTextWithRegex] in 0.0370 seconds.
VERBOSE: [2016-BUILD-1]: LCM: [ Skip Set ] [[ReplaceText]SetTextWithRegex]
VERBOSE: [2016-BUILD-1]: LCM: [ End Resource ] [[ReplaceText]SetTextWithRegex]
VERBOSE: [2016-BUILD-1]: LCM: [ End Set ]
VERBOSE: [2016-BUILD-1]: LCM: [ End Set ] in 0.6480 seconds.
VERBOSE: Operation 'Invoke CimMethod' complete.
VERBOSE: Time taken for configuration job to complete is 0.741 seconds

Suggested solution to the issue

If Test-TargetResource doesn't find any matches it should return FALSE so it is possible to add additional
entries to a configuration file.

The DSC configuration that is used to reproduce the issue (as detailed as possible)

Configuration Example
{
    Import-DSCResource -ModuleName FileContentDsc

    Node localhost
    {
        ReplaceText SetTextWithRegex
        {
            Path   = 'c:\scratch\firefox.cfg'
            Search = 'lockPref\("browser.download.dir", ".*"\);'
            Type   = 'Text'
            Text   = 'lockPref("browser.download.dir", "N:");'
        }
    }
}

The operating system the target node is running

Version and build of PowerShell the target node is running

PSVersion 5.1.14393.2155

Version of the DSC module that was used ('dev' if using current dev branch)

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.