Replace

The -replace operator performs replacement based on a regular expression. For example, it can be used to replace several instances of the same thing:

PS> 'abababab' -replace 'a', 'c'
cbcbcbcb

In the example, a is the regular expression that dictates what must be replaced. 'c' is the value any matching values should be replaced with.

This syntax can be generalised, as follows:

<Value> -replace <Match>, <Replace-With> 

If the Replace-With value is omitted, the matches will be replaced with nothing (that is, they are removed):

PS> 'abababab' -replace 'a'
bbbb

Regular expressions use parentheses to capture groups. The replace operator can use those groups. Each group may be used in the Replace-With argument. For example, a set of values can be reversed:

'value1,value2,value3' -replace '(.*),(.*),(.*)', '$3,$2,$1' 

The tokens $1, $2, and $3 are references to each of the groups denoted by the parentheses.When performing this operation, the Replace-With argument must use single quotes to prevent PowerShell from evaluating the group references as if they were variables. This problem is shown in the following example. The first attempt works as expected; the second shows an expanded PowerShell variable instead:

PS> $1 = $2 = $3 = 'Oops'
PS> Write-Host ('value1,value2,value3' -replace '(.*),(.*),(.*)', '$3,$2,$1') -ForegroundColor Green
PS> Write-Host ('value1,value2,value3' -replace '(.*),(.*),(.*)', "$3,$2,$1") -ForegroundColor Red

value3,value2,value1
Oops,Oops,Oops

The -replace operator is a incredibly useful and widely used operator in PowerShell.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.201.71