Powershell the switch statement pt 2.

The string value specified in the switch statement’s script block has to exactly match a condition for that condition to equal true. Despite it being unnecessary for exact matches, this would be the same as using the -exact option in a switch statement. There are other options available for use such as -wildcard which lets you use wildcards, and -regex which uses regular expressions. lets look at an example;

$files = dir c:archivedfiles*.txt
switch -wildcard ($files)
*2007*
{
move $_ C:archivedfiles2007
$_.name + ” moved.”

}
*2006*
{
move $_ C:archivedfiles2006
$_.name + ” moved.”
}
default
{
$_.name + ” older than 2006.”
}
}

Ok the section marked by red text uses the wildcard *2007*, which means the filename must contain the string 2007, with any number of characters either before or after. If 2007 is found in a string, then the switch statement moves that file to the 2007 folder and displays a message stating such.

When you wish to use regular expressions, you use the -regex option, such as is shown below.

$files = dir c:archivedfiles*.txt
switch -regex ($files)
{
archive.._200[3-5].txt
{
del $_
$_.name + ” deleted.”
}

archive.._2006.txt
{
move $_ C:archivedfiles2006
$_.name + ” moved.”
}

default
{
move $_ c:archived files2007
$_.name + ” moved.”
}
}

the switch statement in this example uses two regular expressions the first one in red, is the condition block. This condition uses the regular expression archive.._200[3-5].txt to delete any file whose filename begins with “archive” and ends with either _2003.txt, _2004.txt, or _2005.txt. The condition in the blue section of our sample uses the regular expression archive.._2006.txt to move any file that begins with “archive” and ends with _2006.txt to the 2006 folder. The default clause then moves all other files to the 2007 folder. The switch statement also supports the -casesensitive option, which lets you make matches with case sensitivity.

Another good option is -file. This is used when you want to use a file’s contents as the collection. Each line in the file represents an element in the colletion. For example;

switch -regex -file `
C:archivedfilesarchive08_2007.txt
{
“line 1)$” { “Line 1: $_” }
“line 2)$” { “Line 2: $_” }
“line 3)$” { “Line 3: $_” }
“line 4)$” { “Line 4: $_” }
default { “Other line: $_” }
}

This example retrieves the archive08_2007.txt file’s contents. As you can see you must include the file’s pathname after the keyword -file. In the switch statement’s script block, the first condition specifies that a line must end in the string ” line 1)”. If this condition equals true then the phrase “line 1:” is printed followed by the line itself ($_). If none of the four conditions equal true, then the default clause will run.

Leave a Reply