none
Powershell - detecting odd/even computername RRS feed

  • Question

  • Hi All,

    I have the following code as part of a larger script;

    $OddEvenCheck = $ENV:COMPUTERNAME.Substring($ENV:COMPUTERNAME.Length - 1)
    $OddEvenCheck = if ($OddEvenCheck % 2 -eq 0 ) {"even"}
    Elseif ($OddEvenCheck % 2 -eq 1 ) {"odd"}

    The script, in its whole form, is designed to have a list of gateways as variables. It then runs as a startup script and detect the gateway and hostname of the local computer.

    If the computers hostname ends with an odd numeric value and belongs to gateways from site 1 variable then it adds network printer connections from the print server 1.

    If the computer hostname ends with an even numeric value and belongs to gateways from site 1 variable then it adds network printer connections from the print server 2.

    etc etc.

    What I can't quite figure out is how to trap the scenario whereby a computers hostname doesn't end with a numeric. Any advice would be greatly appreciated!

    Adam

    Monday, October 15, 2018 9:24 PM

Answers

  • if($ENV:COMPUTERNAME[-1] -match '0|2|4|6|8'){
        'even'
    }elseif($ENV:COMPUTERNAME[-1] -match '1|3|5|7|9'){
        'odd'
    }else{
        'not numeric'
    }


    \_(ツ)_/

    • Proposed as answer by SWamsley Monday, October 15, 2018 11:55 PM
    • Marked as answer by Adam_231 Tuesday, October 16, 2018 9:06 PM
    Monday, October 15, 2018 9:48 PM

All replies

  • if($ENV:COMPUTERNAME[-1] -match '0|2|4|6|8'){
        'even'
    }elseif($ENV:COMPUTERNAME[-1] -match '1|3|5|7|9'){
        'odd'
    }else{
        'not numeric'
    }


    \_(ツ)_/

    • Proposed as answer by SWamsley Monday, October 15, 2018 11:55 PM
    • Marked as answer by Adam_231 Tuesday, October 16, 2018 9:06 PM
    Monday, October 15, 2018 9:48 PM
  • Or this:

    if($ENV:COMPUTERNAME[-1] -match '\d$'){ 
        if(([int]$matches[0]) % 2){'odd'}else{'even'}
    }else{
        'alpha'
    }


    \_(ツ)_/

    • Proposed as answer by SWamsley Monday, October 15, 2018 11:55 PM
    Monday, October 15, 2018 9:56 PM
  • You actually only need the array index [-1] OR the end of line anchor ($) since they accomplish the same thing.
    Monday, October 15, 2018 11:55 PM