SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 

Use -eq in Powershell

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

The Voice of the DBA

Steve Jones is the editor of SQLServerCentral.com and visits a wide variety of data related topics in his daily editorial. Steve has spent years working as a DBA and general purpose Windows administrator, primarily working with SQL Server since it was ported from Sybase in 1990. You can follow Steve on Twitter at twitter.com/way0utwest

Comments

Leave a comment on the original post [voiceofthedba.wordpress.com, opens in a new window]

Loading comments...