views:

31

answers:

2

I have a string

$string = "Active Directory"

and I want to make another string

Active_Directory_Results.txt

I would like to just do

$otherstring = "$string.Replace(" ","_")_Results.txt"

but that doesn't work out. What would be the correct way to pull this off?

+3  A: 

I'm not on my windows machine right now, but how does $otherstring = $string.Replace(" ","_") + "_Results.txt" work?

Check the invoke-expression command. It allows you to execute code in a string. Like:

PS> $command = '$otherstring = $string.Replace(" ","_") + "_Results.txt"'
PS> Invoke-Expression $command
klausbyskov
Yes indeed but I don't want to use concatenation to do it. Like, how do you execute code inside a string?
MattUebel
@MattUebel I have updated my answer.
klausbyskov
Invoke-Expression : You must provide a value expression on the right-hand side of the '+' operator.At line:2 char:18+ Invoke-Expression <<<< $command + CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException + FullyQualifiedErrorId : ExpectedValueExpression,Microsoft.PowerShell.Commands.InvokeExpressionCommand
MattUebel
Error when trying to run code as suggest in answer^
MattUebel
@MattUebel there was a syntax error in my example. It was missing the quotes around `_Results.txt`.
klausbyskov
+3  A: 

You should not use invoke-expression for that. The original answer is good:

$otherstring = $string.Replace(" ","_") + "_Results.txt"

But really, you can just use a $(subexpression):

$otherstring = "$($string.Replace(" ","_"))_Results.txt"

The $() tells PowerShell to evaluate that BEFORE defining the string.

As an alternative, you can also use string formatting:

$otherstring = "{0}_Results.txt" -f $string.Replace(" ","_")

Proving once again that with scripting languages, there's always more than one right way ...

Jaykul