November 4, 2011

How to replace values in a string

Sometimes you a have a string like ”Cannot find file $1” where you want to replace the $1 by a value (ex: myfile.txt). Sure you can use the –replace operator but there is a much more elegant solution : the –format operator.

$ErrMsg="Cannot find file {0}" -f 'myfile.txt'

$ErrMsg will output :
Cannot find file myfile.txt

You can even use the –format in a multi-value, multi-line way :

$ErrMsg=@"
Filename : {0}
Filepath : {1}
Size     : {2:N} MB
"@ -f 'Myfile.txt','C:\temp',(1234567/1MB)

$ErrMsg will output :
Filename : Myfile.txt
Filepath : C:\temp
Size     : 1,18 MB

No comments:

Post a Comment