Posted On July 2, 2020

PowerShell: Regex Examples

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Regex Examples
# Example 1 Simple 10-digit match
$x='123-456-7890'
[regex]$regex10Digits='\({0,1}\d{0,1}\){0,1}\-{0,1}(\d{3})'
$areaCode=$regex10Digits.Match($x).Groups[1].Value

# Example 2 IP Version 4 Addresses
$defaultInterface=get-wmiobject win32_networkadapterconfiguration -filter "ipenabled='true'"|?{$_.DefaultIpGateway -ne $null}
$regexIpv4 = "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
$ipv4=$defaultInterface.IpAddress|?{$_ -match $regexIpv4}

# Example 3 Social Security Number
$regexSsn='^(?!\b(\d)\1+-(\d)\1+(-){0,1}(\d)\1+\b)(?!123-45-6789|219-09-9999|078-05-1120|457-55-5462)(?!666|000|9\d{2})\d{3}(-){0,1}(?!00)\d{2}(-){0,1}(?!0{4})\d{4}$'
'123456789' -match $regexSsn

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

PowerShell: Check TCP Connections of Server by Port Numbers

# Check-TCP-Connections.ps1# This function will output progress onto the console as well as returning a…

Simple Active Directory & DNS Synchronization Script

@echo offGOTO push_or_pull:push_or_pullset /p action="Type in Push, Pull, or Quit. Press Enter for default action…

PowerShell: Get Spectre Meltdown Patching Versions of Hyper-V Hosts

function getHyperVHostsInForest{ function includeRSAT{ $ErrorActionPreference='stop' [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 #$rsatWindows7x32='https://download.microsoft.com/download/4/F/7/4F71806A-1C56-4EF2-9B4F-9870C4CFD2EE/Windows6.1-KB958830-x86-RefreshPkg.msu' $rsatWindows7x64='https://download.microsoft.com/download/4/F/7/4F71806A-1C56-4EF2-9B4F-9870C4CFD2EE/Windows6.1-KB958830-x64-RefreshPkg.msu' $rsatWindows81='https://download.microsoft.com/download/1/8/E/18EA4843-C596-4542-9236-DE46F780806E/Windows8.1-KB2693643-x64.msu' $rsat1709 = "https://download.microsoft.com/download/1/D/8/1D8B5022-5477-4B9A-8104-6A71FF9D98AB/WindowsTH-RSAT_WS_1709-x64.msu" $rsat1803…