I was writing a quick script to work with files and I only wanted to process one file for each execution of a loop. I could have done this multiple ways, but I threw this together:
$fileEntries = [IO.Directory]::GetFiles(“d:\placeholder”);
$delete = 1;
foreach($fileName in $fileEntries)
{
if ($delete = 1)
{
# do something
$delete = 0;
}
}
When I ran it, it kept deleting everything in the folder. That was really annoying, and it took me a few minutes to spot the problem. I kept thinking my variable wasn’t getting set to a new value, but it was. The problem was it kept getting reset.
I first changed to this, but that produced a PoSh error. That’s because I’m working in PoSh and not C.
$fileEntries = [IO.Directory]::GetFiles(“d:\placeholder”);
$delete = 1;
foreach($fileName in $fileEntries)
{
if ($delete == 1)
{
# do something
$delete = 0;
}
}
Eventually I remembered that I need to compare things with -eq, so I ended up with this, which worked perfectly.
$fileEntries = [IO.Directory]::GetFiles(“d:\placeholder”);
$delete = 1;
foreach($fileName in $fileEntries)
{
if ($delete -eq 1)
{
# do something
$delete = 0;
}
}
Filed under: Blog Tagged: powershell, syndicated