AdilZ
AdilZ

Reputation: 1197

Powershell format string with output from function

Hey guys I am having trouble figuring out how to convert the following function (which requires an input) into a variable

 function Convert-ToLetters ([parameter(Mandatory=$true,ValueFromPipeline=$true)][int] $value)  {
   $currVal = $value;
   $returnVal = '';
   while ($currVal -ge 26) {
      $returnVal = [char](($currVal) % 26 + 65) + $returnVal;
      $currVal =  [int][math]::Floor($currVal / 26)
   }
  $returnVal = [char](($currVal) + 64) + $returnVal;

     return $returnVal
  }

What this Function does is to convert a number into letters.

Now what I want to achieve is to somehow do this:

$convert2letter = Convert-ToLetters()

So that I can do something like

$WR= "$convert2letter($CValue1)" + "-" + "$convert2letter($CValue2)" + "-" + "3"

But Powershell isnt allowing me to do $convert2letter

So what can I do here?

Thanks

Upvotes: 2

Views: 1449

Answers (3)

Bill_Stewart
Bill_Stewart

Reputation: 24575

If I understand your question, you are saying you want to invoke a function whose name is stored in a variable. One way to do this is by embedding a subexpression - $() - in a string and use the invocation/call operator - & to execute the function. For example:

function T {
  param(
    $a
  )
  "Result = $a"
}

$fn = "T"
"We want $(& $fn Test)"

Output:

We want Result = Test

Upvotes: 2

Matt
Matt

Reputation: 46710

Without more information for justifying it I would think instead of this:

$WR= "$convert2letter($CValue1)" + "-" + "$convert2letter($CValue2)" + "-" + "3"

You should just be doing this:

$WR = "$(Convert-ToLetters $CValue1)-$(Convert-ToLetters $CValue2)-3"

which uses subexpressions. Or use the format operator

$WR = "{0}-{1}-3" -f (Convert-ToLetters $CValue1), (Convert-ToLetters $CValue2)

Upvotes: 5

4c74356b41
4c74356b41

Reputation: 72171

New-Alias -Name `$convert2letter -Value Convert-ToLetters

Not sure what you are trying to achieve, this doesn't make a lot of sense.

Upvotes: 1

Related Questions