'Windows Powershell ISE - "Global" variable $SearchFolder causing havoc

Disclaimer: I am pretty new to scripting and my terminology might be off, but I will describe the issue as good as I can.

I executed a script with an undeclared variable $SearchFolder in Windows PowerShell ISE. Here is what happened.

Script's logic: Define two folder variables, say A and B, and move content of A to B

Version 1:

$SearchFolder = "E:\folderA"

$ProcessedFolder = "E:\folderB"

Get-ChildItem $SearchFolder |

Where-Object { $_.Attributes -ne "Directory"} |

ForEach-Object {

#Move-Item -Path $_.FullName -Destination $ProcessedFolder

}

Worked exactly like intended up to here.

I then rearranged my variable naming convention ('Folder' as pre- instead of post-fix). I unfortunately missed out on renaming the variable in the Get-ChildItem line, though, i.e. script looked like:

$FolderSearch = "E:\folderA"

$FolderProcessed = "E:\folderB"

Get-ChildItem $SearchFolder |

Where-Object { $_.Attributes -ne "Directory"} |

ForEach-Object {

#Move-Item -Path $_.FullName -Destination $FolderProcessed

}

In other words: I declared variable $FolderSearch never using, but accidently called (un-declared!?) variable $SearchFolder instead.

I assumed that a script will fail if it encounters an un-declared variable. But it executed and started moving system files and folders from my C: drive (Program Files, Program Files (x86), Users,...) to FolderProcessed! I killed the script pretty quickly, so not entirely sure what it would fetch if left undisturbed. So even though undeclared, $SearchFolder seems to assume some "globally assigned" values.

Anyone who could shed some light on this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source