Powershell parameters and functions

This is a general newb question. Love powershell, but I definitely don't get something here:

I am creating a simple function to replicate a string x times. I have some kind of weird problem with a parameter - it doesn't seem to recognize the second parameter.
When I run the function, it returns an empty string. Also, I think it combines 2 parameters into 1. Here is 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 am a point source to load it:
. .\RepeatString.ps1
then I will do it like this:
Repeat-string("x", 7)
I was expecting a string of 7 x. I got an empty string.

, "for". "-lt $repeat" "-lt 5", . , ( ):
Repeat-String ( "x", 7)
"x 7x 7x 7x 7x 7"
, $str $repeat , 2 . , ?

+5
4

,

Repeat-string "x" 7

PowerShell , (), . , .

+17

, () N :

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

PS > Repeat-String JMarsch 3
JMarschJMarschJMarsch
+6

:

" , . ".

授人以魚不如授人以漁 Shòu rén yǐ yú bùrú shòu rén yǐ yú. ( , ! , , , , ...: -)

, , JMarsch PowerShell, , "" , @JaredPar . , !

Simple-Talk.com, Rabbit Hole: PowerShell Pipelines, Functions and Parameters - . , f, , .

f(1,2,3)
f (1,2,3)
f 1,2,3
f (1 2 3)
f 1 2 3

PDF , .

: PowerShell Functions Quick Reference

(, , , ...)

+6

, JaredPar .

I like to use the built-in range function ..for this too: (note that I start with 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
0
source

All Articles