MattUebel
MattUebel

Reputation: 2857

Include code in string definition?

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?

Upvotes: 2

Views: 291

Answers (2)

Jaykul
Jaykul

Reputation: 15824

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 ...

Upvotes: 4

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

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

Upvotes: 2

Related Questions