Problems with using Switch statement

Welcome Forums General PowerShell Q&A Problems with using Switch statement

This topic contains 1 reply, has 2 voices, and was last updated by

5 years, 1 month ago.

  • Author
  • #12461

    Points: 0
    Rank: Member

    This script runs without error, but I don't think the switch statement has been implemented correctly. The results apply all registry entries based on the lines of code in the switch block. It should "not" apply $RBM01, because it does not exist in $app.

    Please help. Code below

    New-Item -Path HKLM:\Software\Geneva\Warehousing -Name Packages
    $app = get-childitem c:\install\$computername
    $computername = (Get-WmiObject -Class Win32_ComputerSystem).__Server
    $Bginfo = set-itemproperty -Path HKLM:\Software\Geneva\Warehousing\Packages -name 'trial_03' -value NOV0173
    $RBM03 = set-itemproperty -Path HKLM:\Software\Geneva\Warehousing\Packages -name 'support_03' -value NOV01797
    $RBM01 = set-itemproperty -Path HKLM:\Software\Geneva\Warehousing\Packages -name 'trial_01' -value NOV01796
    switch ($app)
    ($app -eq '*trial_03*') {$Bginfo}
    ($app -eq '*support_03*') {$RBM03}
    ($app -eq '*trial_01*') {$RBM01}

  • #12473

    Points: 0
    Rank: Member

    I will refer to code lines using the number 1-12, to make it easier to talk about the code.

    On line 4-6 you're setting your registry keys, before you have even come to the switch statement. Therefore you will always be creating the registry keys, no matter the value of $app.

    Line 7-12 will make the code return (write as output, Write-Output) one of the item properties saved on line 4-6, depending on the value of the $app variable, or at least could have. However, -eq doesn't do pattern matching and the "*" character is not a valid character in a file name, so I'm guessing you really want to a wildcard search. You should then write your switch statement similar to the following:

    switch -Wildcard ($app)
    	"*trial_03*" { < # do trial 03 stuff here#> }
    	"*support_03*" { < # do support 03 stuff here#> }
    	"*trial_01*" { < # do trial 01 stuff here#> }

    Additionally, on line 3 you're setting the $computername variable, but you're using it the line before, on line 2. I'm guessing this is not what you want to do, so these lines should probably swap places.

The topic ‘Problems with using Switch statement’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort