Search code examples
powershelllocal-variablespowershell-module

Setting a (string) variable equal to another (string) variable including modifications


I'm trying to get better at reusable PowerShell (v5.1, but v-agnostic) scripting at scale with libraries, and I have a very simple task I'll use for illustration. Coming from C# the pseudocode to create a variable from another, with some changes would look something like

string somevar = "foo";
string someothervar = DoSomethingTo(somevar); // lots of variations HERE
Debug.Print someothervar;

Let's say it's a simple replace operation. I won't bother writing that in C# (or PoSh) but since it's fundamentally a scripting language, every blog- or documentation-type example I can find for replace looks something like

> $somevar = "foo"
> {# here are 3 ways to say replace in PowerShell}
> # here is some console output of what happens when you do that

I do not care about console output. I care about understanding all the PowerShell-native ways I can make a $someothervar out of operation(s) on $somevar, e.g. replacing some part of it. (I know I can essentially invoke .NET.)

If I were to ask this question in an even worse way, it would be something like "how do you set local PowerShell variables in inline operations using other PowerShell variables and/or parameters".


Solution

  • In PowerShell any output can be assigned to a variable. If it isn't assigned or otherwise consumed it will output to the host, usually the console.

    Your example derived from pseudo code might be something like:

    $SomeOtherVar = $SomeVar -replace "one", "two"
    

    The same would be true if you invoked a .Net method on the string:

    $SomeOtherVar = $SomeVar.Replace( "one", "two" )
    

    Also important is assigning the output of a command which can be a cmdlet, function or even a command line executable.

    Note: that calling functions & cmdlets is a little different in PowerShell. Don't specify arguments parenthetically. Separate parameters and arguments with spaces and/or use the named parameters.

    $SomeOtherVar = Get-SomeData $SomeVar
    
    $SomeOtherVar = Ping $SomeVar
    

    The summary answer to your question is anything PowerShell outputs can be assigned to a variable. So, literally anything you do to $SomeVar that generates output even if the output is null can be assigned to $SomeOtherVar

    Responding to Comment / Additional Example:

    $SomeVar = 'foo'
    $SomeOtherVar = $SomeVar -replace 'foo', 'bar'
    $SomeOtherVar
    

    Output: bar