tags:

views:

374

answers:

3

This is a total newb question. Loving powershell, but 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
then I Execute 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. Any idea what I'm doing wrong?

+8  A: 

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

Repeat-string "x" 7

In PowerShell anytime 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.

JaredPar
Thanks! I knew I was doing something stupid -- just wasn't sure what.
JMarsch
@JMarsch, everyone gets tripped up by this at least once. It's really annoying :(
JaredPar
I hate this! But you get used to it...
Philippe
A: 

Of course JaredPar is right.

I like to use the built in range function .. for this too: (notice I start at 1 instead of 0)

Function Repeat-String([string]$str, [int]$repeat) {
  $builder = new-object System.Text.StringBuilder
  1..$repeat | %{ [void]$builder.Append($str) }
  return $builder.ToString()
}

Repeat-string "x" 7
John Weldon
Thanks -- didn't know about the range function. I'm going to have to fit a book on powershell into my reading list. (I guess at this point, I might as well look/wait for a powershell 2.0 book)
JMarsch
+4  A: 

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
Shay Levy
Every new thing I learn about powershell just shows me how cool it is. Thanks for sharing that, Shay +1
JMarsch
PowerShell ROCKS ;-)
Shay Levy