Reputation: 390
I have a series of files that need to be filtered before being added to a job queue. That job queue uses the file type as a parameter of a function. What I'm currently using is this:
foreach ($currentFile in $ListOfTestFiles)
{
if ($currentFile.Name.Contains("Test1"))
{
$ParameterSet="Type1,$SomeOtherVariable"
}
if ($currentFile.Name.Contains("Test2"))
{
$ParameterSet="Type2,$SomeOtherVariable"
}
if ($currentFile.Name.Contains("Test3"))
{
$ParameterSet="Type3,$SomeOtherVariable"
}
if ($currentFile.Name.Contains("Test4"))
{
$ParameterSet="Type4,$SomeOtherVariable"
}
$JobArray += Start-Job -ScriptBlock $func -ArgumentList $ParameterSet
$JobArray | Receive-Job -Wait
}
Is there a way to slim this down with a switch statement?
Upvotes: 2
Views: 13127
Reputation: 61
You can do the following:
switch ($currentFile)
{
{$_.name.contains("Test1")} {$ParameterSet="Type1,$SomeOtherVariable"}
{$_.name.contains("Test2")} {$ParameterSet="Type2,$SomeOtherVariable"}
Default {}
}
Upvotes: 3
Reputation: 1867
foreach($currentFile in $listOfTestFiles)
{
switch -wildcard ($currentFile.Name)
{
"*Test1*" {$ParameterSet="Type1,$SomeOtherVariable"}
"*Test2*" {$ParameterSet="Type2,$SomeOtherVariable"}
"*Test3*" {$ParameterSet="Type3,$SomeOtherVariable"}
"*Test4*" {$ParameterSet="Type4,$SomeOtherVariable"}
default {"Default Behaviour"}
}
$JobArray += Start-Job -ScriptBlock $func -ArgumentList $ParameterSet
$JobArray | Receive-Job -Wait
}
Note that I didn't test this code, but I followed Microsoft example from here
Upvotes: 8