functions/string/Set-PSUString.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
function Set-PSUString
{
<#
    .SYNOPSIS
        Replaces a part of the input string with another.
     
    .DESCRIPTION
        Replaces a part of the input string with another.
        Supports both regex replace as well as regular .replace().
     
    .PARAMETER InputString
        The stringgs on which replacement will be performed.
     
    .PARAMETER What
        What should be replace?
     
    .PARAMETER With
        With what should it be replaced?
     
    .PARAMETER Simple
        By default, this function uses regex replace. Sometimes this may not be desirable.
        This switch enforces simple replacement, not considering any regular expression functionality.
     
    .PARAMETER Options
        Default: IgnoreCase
        When using regex replace, it may become desirable to specify options to the system.
     
    .EXAMPLE
        "abc ABC" | replace b d
     
        Returns "adc AdC".
     
    .EXAMPLE
        "abc ABC" | replace b d -Options None
     
        Returns "adc ABC"
     
    .EXAMPLE
        "abc \def" | replace "\de" "&ed" -s
     
        Returns "abc &edf"
#>

    [CmdletBinding(DefaultParameterSetName = "regex")]
    Param (
        [Parameter(ValueFromPipeline = $true)]
        [string[]]
        $InputString,
        
        [Parameter(Position = 0, Mandatory = $true)]
        [string]
        $What,
        
        [Parameter(Position = 1, Mandatory = $true)]
        [string]
        $With,
        
        [Parameter(ParameterSetName = "Simple")]
        [Alias('s')]
        [switch]
        $Simple,
        
        [Parameter(ParameterSetName = "Regex")]
        [System.Text.RegularExpressions.RegexOptions]
        $Options = [System.Text.RegularExpressions.RegexOptions]::IgnoreCase
    )
    
    begin { }
    process
    {
        foreach ($line in $InputString)
        {
            if ($Simple) { $line.Replace($What, $With) }
            else { [regex]::Replace($line, $What, $With, $Options) }
        }
    }
    end { }
}
Import-PSUAlias -Name replace -Command Set-PSUString