I've been using a cmd/batch file to create a locationid variable based on what IP range the computer is in. I need to do a similar function using powershell. Any advise would be welcomed.
As an example of the code I'm using in the batch file:
For /F "Delims==" %%G In ('Set octet 2^>NUL')Do Set "%%G="
For /F "Tokens=2 Delims=:" %%G In (
'"%__AppDir__%ipconfig.exe 2>NUL|%__Appdir__%find.exe "IPv4""'
)Do For /F "Tokens=1-4Delims=. " %%H In ("%%G"
)Do Set "octet1=%%H"&Set "octet2=%%I"&Set "octet3=%%J"&Set "octet4=%%K"
Set octet>NUL 2>&1||(Echo IPConfig failed to retrieve an IP address.
Pause&GoTo :EOF)
Set "BuildingLOC="
If %octet1% Equ 10 If Defined octet2 (
If %octet2% GEq 6 If %octet2% LEq 7 Set "BuildingLOC=VM"
If %octet2% GEq 10 If %octet2% LEq 19 Set "BuildingLOC=ADM"
)
CodePudding user response:
Working with IP Octets:
function Get-HostIP {
[CmdletBinding()]
[OutputType([string])]
param ()
# https://stackoverflow.com/a/44685122/4190564
$Return = (
Get-NetIPConfiguration | Where-Object {
$null -ne $_.IPv4DefaultGateway -and $_.NetAdapter.Status -ne "Disconnected"
}
).IPv4Address.IPAddress
return $Return
}
Function Get-IPOctets {
[CmdletBinding()]
[OutputType([int[]])]
param (
[Parameter(Mandatory = $true, Position = 0)]
[string]$IPAddress
)
if( $IPAddress -match '(?<Octet1>\d )\.(?<Octet2>\d )\.(?<Octet3>\d )\.(?<Octet4>\d )') {
return $Matches.Octet1, $Matches.Octet2, $Matches.Octet3, $Matches.Octet4
} else {
return 0, 0, 0, 0
}
}
$Octet1, $Octet2, $Octet3, $Octet4 = Get-IPOctets (Get-HostIP)
if($Octet1 -eq 10) {
switch ($Octet2) {
{$_ -in 6..7} {$BuildingLOC = 'VM'; break}
{$_ -in 10..19} {$BuildingLOC = 'ADM'; break}
default {$BuildingLOC = 'Other'; break}
}
} else {
$BuildingLOC = 'Invalid'
}
Write-Host "IPType: $BuildingLOC"
Working with first 3 letters of Computer Name:
if($HostName = [System.Net.Dns]::GetHostName()) {
if($HostName.Substring(0, 3) -eq 'ABC') {
Write-Host "Computer name matches"
} else {
Write-Host "Computer name does not match "
}
} else {
Write-Host "No computer name"
}