Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameters and PowerShell functions

Tags:

powershell

I'm definitely not getting something here:

I'm creating a simple function to replicate a string x times. I am having some weird problem with the parameter -- it doesn't seem to be recognizing the second parameter. When I run the function, it returns an empty string. Further, I think it's lumping the 2 parameters into 1. Here's my code:


Function Repeat-String([string]$str, [int]$repeat) {
  $builder = new-object System.Text.StringBuilder
  for ($i = 0; $i -lt $repeat; $i++) {[void]$builder.Append($str)}
  $builder.ToString()
}

First I dot-source it to load it:

. .\RepeatString.ps1

And then I execute it like this:

Repeat-string("x", 7)
I expected a string of 7 x's. I got an empty string.

I went poking around some more, and I changed the "for" loop. I replaced the "-lt $repeat" part with "-lt 5", so that I would get a fixed number of repeats. When I did that, I got the following output (without the quotes):

Repeat-String("x", 7)

"x 7x 7x 7x 7x 7"

It looks as though it is concatenating the $str and $repeat parameters instead of treating them like 2 separate parameters. What am I doing wrong?

like image 733
JMarsch Avatar asked Jun 05 '09 19:06

JMarsch


2 Answers

The problem is that you need to convert your code to the following

Repeat-string "x" 7

In PowerShell, any time you put a group of values inside ()'s, you are creating an array. This means in your sample you're actually passing an array to the function as a single parameter.

like image 67
JaredPar Avatar answered Nov 29 '22 15:11

JaredPar


Here's a better way, just multiply your (any) string by N repeats:

PS > function Repeat-String([string]$str, [int]$repeat) {  $str * $repeat }
PS > Repeat-String x 7
xxxxxxx

PS > Repeat-String JMarsch 3
JMarschJMarschJMarsch
like image 31
Shay Levy Avatar answered Nov 29 '22 15:11

Shay Levy