Typical string formatting in powershell for instance to use padding or specifying number can be written like this:
>>> "x={0,5} and y={1:F3}" -f $x, $y
x= 10 and y=0.333
But in Powershell you can also use string interpolation like
>>> $x=10
>>> $y=1/3
>>> "x=$x and y=$y"
x=10 and y=0.333333333333333
And in C# string interpolation also supports the formatting specifiers:
> var x = 10;
> var y = 1.0/3.0;
> $"x={x,5} and y = {y:F2}";
"x= 10 and y = 0.33"
Is there a way to have that in Powershell? I've tried many combinations like
>>> "var=$($var, 10)"
var=10 10
but none of them work. Is this supported? Or is there a succinct way to call into C# to use it?
update as Mathias answers and as confirmed on Powershell's github this is currently not supported, so I made a feature request here
"var={0,10}" -f $var
like in my second code example. Well, because I like inline string interpolation, am used to the syntax from other languages, it's somewhat shorter and I find it more readable (usually). – Spillage$var
? In that case, you could use the String methodPadLeft
, something like"var=$($var.ToString().PadLeft(5))"
– Freehand-f
string format operator. there is [apparently] no other way in powershell to do that stuff. – Delete"$(' '*10)$var"
– Beezer