Search code examples
variablespowershellevent-log

Powershell incremental number at start of string


Attempting to increment the start of a string with a number.

foreach ($var in $variables) {
New-EventLog -computername $PC -LogName $var -source $var
}

I wish to increment $var with a number, so the result is like so: $var = 1Server $var = 2Server etc etc.

How do I add in incremental number at the beginning of $var in my foreach statement?

I tried with:

$a = 1
foreach ($var in $variables) {
New-EventLog -computername $PC -LogName ($a++, $var) -source $var
}

But no dice.


Solution

  • You can use the format operator -f to insert the value of $a in the parameter for the Logname

    $a = 1
    foreach ($var in $variables) {
        New-EventLog -computername $PC -LogName ("{0}$var" -f $a++) -source $var
    }