Home > Software engineering >  Powershell ToString() behaviour - replacing 0 in a string during ForEach-Object {$_.ToString('t
Powershell ToString() behaviour - replacing 0 in a string during ForEach-Object {$_.ToString('t

Time:07-02

I've encountered some Powershell behaviour that I didn't expect while using ForEach-Object and ToString. Digits are being replaced automatically and I can't quite graps the rule for the substitution from the output alone.

Here's a small simplified example:

PS C:\Users\Telefonmann> 1..3 | ForEach-Object {$_.ToString('test_0_1')}
test_1_1
test_2_1
test_3_1

PS C:\Users\Telefonmann> 1..3 | ForEach-Object {$_.ToString('test_0_0')}
test_0_1
test_0_2
test_0_3

PS C:\Users\Telefonmann> 1..3 | ForEach-Object {$_.ToString("test_0$_\_0")}
test_01_1
test_02_2
test_03_3

PS C:\Users\Telefonmann> 1..3 | ForEach-Object {$_.ToString("test_0$_\_$_")}
test_11_1
test_22_2
test_33_3

In the first example the 0 is replaced, in the second only the last 0, in the third the placeholder and the 0 are replaced and in the last example the 0 and, of course, the placeholders are replaced. Does Powershell just see a string with a 0 and then assumes that the last 0 in any string is supposed to be a counter?

What's the term for this behaviour / is there some documentation for it? How do I disable it?

CodePudding user response:

This is not Powershell doing. .ToString is a .net method.

You can "disable it" by not using the parameter, which is for formatting.

ToString(IFormatProvider)

Converts the numeric value of this instance to its equivalent string representation using the specified culture-specific format information.

You are formatting your integer into a string using the IformatProvider .net interface, which is responsible for the behaviors you are seeing.

To apply modifications in your string, simply do something like this.

1..3 | ForEach-Object { ("test_0_$_") }

References

.Net - Formatting types

Int32.ToString

CodePudding user response:

An idiom like to generate computernames is:

1..3 | % tostring comp000

comp001
comp002
comp003

You can escape a code with a backslash like in this ip address example:

1..3 | % tostring 192\.168\.\0\.0

192.168.0.1
192.168.0.2
192.168.0.3
  • Related