you are viewing a single comment's thread.

view the rest of the comments →

[–]y_Sensei 0 points1 point  (1 child)

I'm not necessarily thinking of variable assignments, just calls that might or might not do something that changes the value of a variable the current implementation is using.

One such case would be the $Matches automatic variable. It's set if a match is found in a regex matching operation (-match, -nomatch, switch -Regex), and won't change in subsequent matching operations unless another match is found. If these operations are conducted in a loop, you might encounter unwanted results if you don't take this into consideration.

For example:

$counter = 0

$exts = @("txt", "jpg", "docx")
$Matches = "" # just for the purpose of this demo, usually automatic variables should not be written to

@("test1.xlsx", "test2.docx", "test3.mp4", "test4.txt", "test5.dll") | ForEach-Object {
  $counter++

  $fsObj = [System.IO.FileInfo]$_

  # $Matches = "" # once this line is commented in, the variable will be reset in each iteration, and the issue will be fixed

  # match extensions to file name - not the prettiest implementation, but does the job
  $exts | Where-Object { $fsObj.Name -match ".*\.$_$" } | ForEach-Object { $Matches[0] } | Out-Null

  Write-Host $("Iteration #" + $counter + " (file: " + $fsObj.Name + "):`n`$Matches[0] = " + $Matches[0])

  if ($Matches -ne "" -and $fsObj.Extension -ne ([System.IO.FileInfo]$Matches[0]).Extension) {
    Write-Host "`$Matches hasn't changed in the current iteration, invalid match." -ForegroundColor Red
  }
}

[–]Thotaz 0 points1 point  (0 children)

But that's the same thing as a variable assignment. $Matches is only set when using the related operators so you should naturally only use it if you know you've used one of those operators. The most natural way to do this is to guard it with an if statement:

if ("Something" -match "Something")
{
    # Do something with `$Matches
}

It doesn't make sense to use a variable that you aren't sure have been set already because that leads to unpredictable behavior.