Skip to content

ReplaceText

dscbot edited this page Jun 12, 2024 · 7 revisions

ReplaceText

Parameters

Parameter Attribute DataType Description Allowed Values
Path Key String The path to the text file to replace the string in.
Search Key String The RegEx string to use to search the text file.
Type Write String Specifies the value type to use as the replacement string. Defaults to 'Text'. Text, Secret
Text Write String The text to replace the text identified by the RegEx. Only used when Type is set to 'Text'.
Secret Write PSCredential The secret text to replace the text identified by the RegEx. Only used when Type is set to 'Secret'.
AllowAppend Write Boolean Specifies to append text to the file being modified. Adds the ability to add a configuration entry.
Encoding Write String Specifies the file encoding. Defaults to ASCII ASCII, BigEndianUnicode, BigEndianUTF32, UTF8, UTF32

Description

The resource is used to replace strings matching a regular expression in a text file.

It can be used to replace strings matched with a regular expression with either a text string or a secret which is provided in the password of a credential object.

Examples

Example 1

Set all occrurances of the string %secret% to be the value in the password set in the parameter $Secret PSCredential object in the file c:\inetpub\wwwroot\default.htm.

Configuration ReplaceText_ReplacePlainSecretText_Config
{
    param
    (
        [Parameter()]
        [ValidateNotNullorEmpty()]
        [PSCredential]
        $Secret
    )

    Import-DSCResource -ModuleName FileContentDsc

    Node localhost
    {
        ReplaceText SetSecretText
        {
            Path   = 'c:\inetpub\wwwroot\default.htm'
            Search = '%secret%'
            Type   = 'Secret'
            Secret = $Secret
        }
    }
}

Example 2

Set all occrurances of the string %appname% to be Awesome Appin the filec:\inetpub\wwwroot\default.htm`.

Configuration ReplaceText_ReplacePlainText_Config
{
    Import-DSCResource -ModuleName FileContentDsc

    Node localhost
    {
        ReplaceText SetText
        {
            Path   = 'c:\inetpub\wwwroot\default.htm'
            Search = '%appname%'
            Type   = 'Text'
            Text   = 'Awesome App'
        }
    }
}

Example 3

Set all occrurances of a string matching the regular expression <img src=['``"][a-zA-Z0-9.]*['``"]> with the text <img src="imgs/placeholder.jpg"> in the file c:\inetpub\wwwroot\default.htm

Configuration ReplaceText_ReplaceRegexText_Config
{
    Import-DSCResource -ModuleName FileContentDsc

    Node localhost
    {
        ReplaceText SetTextWithRegex
        {
            Path   = 'c:\inetpub\wwwroot\default.htm'
            Search = "<img src=['`"][a-zA-Z0-9.]*['`"]>"
            Type   = 'Text'
            Text   = '<img src="imgs/placeholder.jpg">'
        }
    }
}
Clone this wiki locally