top of page

PowerShell | Compare Odd or Even Substring

PowerShell's Substring method is a useful way to extract parts of a string based on their position within the string. Below are the details on how to use the Substring method in PowerShell:

​

Basic Usage

The Substring method is used to get a portion of a string starting from a specified index. Here’s the basic syntax:

$string.Substring(startIndex)
 

Example:

​

$string = "Hello, World!"
$substring = $string.Substring(7)
Write-Output $substring  # Output: "World!"

In PowerShell, you can use the -contains operator to check if an array contains a specific item, and the -notcontains operator to check if it does not contain a specific item. However, for strings, you typically use the -like, -match, or -contains methods for similar purposes.

​

-contains Operator

The operator used to determine if array contains particular element.

$array = @(1, 2, 3, 4, 5)

if ($array -contains 3) {
    Write-Output "Array contains the value 3"
} else {
    Write-Output "Array does not contain the value 3"
}

Results: Array contains the value 3

And the -NotContains Does the Opposite.

PowerShell Script Odd/Even Separate by Last Character
​

Issue: 100's of workstations to patch with uncommon naming scheme

Descision: Schedule by splitting up the odd and even numbered systems

Solution: separate them by the last digit

  • Char Test-Dev Week 1

  • Even Set Patched Week 2

  • Odd Set Patched Week 3

OddEven.jpg

<#
    .SYNOPSIS

           PowerShell Script Imports Data and Sorts by End Char \ Odd\Even\Char
    .DESCRIPTION

           Pull Data from TxT

           End Result Output to Corresondig Files for Char\Odd\Even Last Char Review

   .Author

           Scott Head

           ScriptsByScott.com
#>

# Get Computers from File
$Computers = Get-Content C:\temp\ODD-Even.txt
#Array of Even Numbers
$EvenArray=@(2,4,6,8,0)
#Array of Odd Numbers
$OddArray=@(1,3,5,7,9)
#---------- Da Loop ---------
Foreach($Comp in $Computers){
    #Get Length of Computer Name Minus 1
    $Length = $Comp.Length - 1
    #Acquire the Substring of the Computer Name
    $Substring =  $($Comp.Substring($Length))
    #Check to see if Substring, last digiat in Computer Name is Even
    if($EvenArray -Contains $Substring){$Comp | Tee-Object C:\temp\Even.txt -Append}
    #Check to See if Substring, Last Digist of COmputer Name is Odd
    if($OddArray -Contains $Substring){$Comp | Tee-Object C:\temp\Odd.txt -Append}
    #Check if Not End in Numeric 
    if(($OddArray -NotContains $Substring) -and ($EvenArray -NotContains $Substring)){
        #If Computer Does Not End with a Number
        $Comp | Tee-Object C:\temp\NotDigit.txt -Append
    }
}

bottom of page