I want to generate a 2048-bit prime number via the buildin cryptography provider in Powershell. This is the code I have so far, but testing the result via Rabin-Miller Test is telling me, that the number is NOT prime. What is wrong here?
$rsa = [System.Security.Cryptography.RSA]::Create(2048)
$format = [System.Security.Cryptography.CngKeyBlobFormat]::GenericPrivateBlob
$bytes = $rsa.Key.Export($format)
[bigint]$prime = 0
foreach($b in $bytes) {$prime = ($prime -shl 8) + $b}
$prime
This link tells me, that the BLOB should contain both RSA primes, but for any reason I am not able to get that info as expected: https://learn.microsoft.com/en-us/windows/win32/seccrypto/rsa-schannel-key-blobs#private-key-blobs
Finally I solved it after digging a bit deeper into the generic BLOB-format. The learning point here is the fact, that a 4096 RSA key includes two 2048-bit primes. One is on the last 256 bytes in the BLOB and the other prime is in the 256 bytes in front of that.
Here is the working code:
# generating two random 2048-bit PRIME numbers:
cls
$rsa = [System.Security.Cryptography.RSA]::Create(4096)
$key = $rsa.Key.Export('PRIVATEBLOB')
$len = $key.Length
$Pb = [byte[]]::new(256+1)
[array]::Copy($key, $len-512, $Pb, 1, 256)
[array]::Reverse($Pb)
$P = [bigint]$Pb
write-host $P
# optionally same for the second prime in the BLOB:
$Qb = [byte[]]::new(256+1)
[array]::Copy($key, $len-256, $Qb, 1, 256)
[array]::Reverse($Qb)
$Q = [bigint]$Qb
write-host $Q
# optionally here the Test-Function:
function Is-PrimeRabinMiller ([BigInt] $Source, [int] $Iterate) {
if ($source -eq 2 -or $source -eq 3) {return $true}
if (($source -band 1) -eq 0) {return $false}
[BigInt]$d = $source - 1;
$s = 0;
while (($d -band 1) -eq 0) {$d = $d -shr 1; $s++;}
if ($source.ToByteArray().Length -gt 255) {
$sourceLength = 255
}
else {
$sourceLength = $source.ToByteArray().Length
}
$rngProv = [System.Security.Cryptography.RNGCryptoServiceProvider]::Create()
[Byte[]] $bytes = $sourceLength
[BigInt]$a = 0
foreach ($i in 1..$iterate) {
do {
$rngProv.GetBytes($bytes)
$a = [BigInt]$bytes
} while (($a -lt 2) -or ($a -ge ($source - 2)))
[BigInt]$x = ([BigInt]::ModPow($a,$d,$source))
if ($x -eq 1 -or ($x -eq $source-1)) {continue}
foreach ($j in 1..($s-1)) {
$x = [BigInt]::ModPow($x, 2, $source)
if ($x -eq 1) {return $false}
if ($x -eq $source-1) {break}
}
return $false
}
return $true
}
if (Is-PrimeRabinMiller $P 42) {"P is prime!"}
if (Is-PrimeRabinMiller $Q 42) {"Q is prime!"}
Also I created a small function based on the above findings, that generates a random large prime numer:
function get-RandomPrime {
Param (
[parameter(Mandatory=$true)]
[ValidateRange(256, 8192)]
[ValidateScript({$_ % 8 -eq 0})]
[int]$bitLength
)
$rsa = [System.Security.Cryptography.RSA]::Create($bitLength*2)
$key = $rsa.Key.Export('PRIVATEBLOB')
$len = $key.Length
$byteLength = [int]$bitLength/8
$bytes = [byte[]]::new($byteLength+1)
[array]::Copy($key, $len-$byteLength, $bytes, 1, $byteLength)
[array]::Reverse($bytes)
[bigint]$bytes
}
$prime = get-RandomPrime -bitLength 2048
write-host "`nprime (DEC):" $prime
write-host "`nprime (HEX):" $prime.ToString('X2').SubString(1)
I'm just learning the basics of powershell and have a task - create pwsh script which accepts 3 incoming parameters (all are mandatory):
first parameter, value address_1, it's IP address with the format x.x.x.x
second parameter, value address_2, it's IP address with the format x.x.x.x
third parameter, value mask, value in the format x.x.x.x or xx (255.0.0.0 or 8)
This script should check address_1 and address_2 belong to the same network or not. Results in output console, yes or no. As I mentioned before incoming parameters not allow to accept not valid arguments, it should show error.
Can someone explain, how I can do that. I will be very grateful for your help.
As per my comment. This stuff already exists for years now, thus no need to try and write this from scratch, unless it's a homework assignment, or you are pushing yourself to learn to do it.
Search is your friend.
'powershell ipv4 address range to cidr'
The first hit in the results...
https://www.kittell.net/code/powershell-ipv4-range
...and the author's examples:
# IPv4 Range
function New-IPRange ($start, $end)
{
# created by Dr. Tobias Weltner, MVP PowerShell
$ip1 = ([System.Net.IPAddress]$start).GetAddressBytes()
[Array]::Reverse($ip1)
$ip1 = ([System.Net.IPAddress]($ip1 -join '.')).Address
$ip2 = ([System.Net.IPAddress]$end).GetAddressBytes()
[Array]::Reverse($ip2)
$ip2 = ([System.Net.IPAddress]($ip2 -join '.')).Address
for ($x=$ip1; $x -le $ip2; $x++)
{
$ip = ([System.Net.IPAddress]$x).GetAddressBytes()
[Array]::Reverse($ip)
$ip -join '.'
}
}
# IPv4 Range - Example
New-IPRange 192.168.10.10 192.168.10.20
# broadcast IPv4 address from a CIDR range
function Get-Broadcast ($addressAndCidr)
{
$addressAndCidr = $addressAndCidr.Split("/")
$addressInBin = (New-IPv4toBin $addressAndCidr[0]).ToCharArray()
for($i=0;$i -lt $addressInBin.length;$i++)
{
if($i -ge $addressAndCidr[1])
{
$addressInBin[$i] = "1"
}
}
[string[]]$addressInInt32 = #()
for ($i = 0;$i -lt $addressInBin.length;$i++)
{
$partAddressInBin += $addressInBin[$i]
if(($i+1)%8 -eq 0)
{
$partAddressInBin = $partAddressInBin -join ""
$addressInInt32 += [Convert]::ToInt32($partAddressInBin -join "",2)
$partAddressInBin = ""
}
}
$addressInInt32 = $addressInInt32 -join "."
return $addressInInt32
}
# IPv4 Broadcast - Example
Get-Broadcast 192.168.10.10/27
# detect if a specified IPv4 address is in the range
function Test-IPinIPRange ($Address,$Lower,$Mask)
{
[Char[]]$a = (New-IPv4toBin $Lower).ToCharArray()
if($mask -like "*.*")
{
[Char[]]$b = (New-IPv4toBin $Mask).ToCharArray()
}
else
{
[Int[]]$array = (1..32)
for($i=0;$i -lt $array.length;$i++)
{
if($array[$i] -gt $mask){$array[$i]="0"}else{$array[$i]="1"}
}
[string]$mask = $array -join ""
[Char[]]$b = $mask.ToCharArray()
}
[Char[]]$c = (New-IPv4toBin $Address).ToCharArray()
$res = $true
for($i=0;$i -le $a.length;$i++)
{
if($a[$i] -ne $c[$i] -and $b[$i] -ne "0")
{
$res = $false
}
}
return $res
}
# IPv4 In Range - Example
Write-Output "`r`nTest If IP In Range - 192.168.23.128/25"
Test-IPinIPRange "192.168.23.200" "192.168.23.12" "255.255.255.128"
Write-Output "`r`nTest If IP In Range - 192.168.23.127/24"
Test-IPinIPRange "192.168.23.127" "192.168.23.12" "24"
# convert an IPv4 address to a Bin
function New-IPv4toBin ($ipv4)
{
$BinNum = $ipv4 -split '\.' | ForEach-Object {[System.Convert]::ToString($_,2).PadLeft(8,'0')}
return $binNum -join ""
}
# IPv4 To Bin - Example
Write-Output "`r`nIP To Bin"
New-IPv4toBin 192.168.10.10
# convert a Bin to an IPv4 address
function New-IPv4fromBin($addressInBin)
{
[string[]]$addressInInt32 = #()
$addressInBin = $addressInBin.ToCharArray()
for ($i = 0;$i -lt $addressInBin.length;$i++)
{
$partAddressInBin += $addressInBin[$i]
if(($i+1)%8 -eq 0)
{
$partAddressInBin = $partAddressInBin -join ""
$addressInInt32 += [Convert]::ToInt32($partAddressInBin -join "",2)
$partAddressInBin = ""
}
}
$addressInInt32 = $addressInInt32 -join "."
return $addressInInt32
}
# IPv4 From Bin - Example
Write-Output "`r`nIP From Bin - 192.168.23.250"
New-IPv4fromBin "11000000101010000001011111111010"
Write-Output "`r`nIP From Bin - 192.168.10.10"
New-IPv4fromBin "11000000101010000000101000001010"
# CIDR To IPv4 Range - Example
Write-Output "`r`nIP CIDR to Range"
New-IPRange "192.168.23.120" (Get-Broadcast "192.168.23.120/25")
You of course can refactor the above with the Validate code already provided to you by the others.
Some of the documentation can seem over-whelming on frist read, so here's a working framework to study and get you started. The [ValidatePattern()] and [ValidateScript()] attributes validate IPv4 address format and valid value range and errors will be thrown if the conditions they specify aren't met.
Perform you domain comparision in the Process block and branch conditionally on the result. I leave that to you.
Function AddressTest
{
Param(
[Parameter(Mandatory,Position = 0)]
[ValidatePattern('^(\d{1,3}\.){3}\d{1,3}$')]
[ValidateScript({[Int[]](($_.Split('.')) -le 255).Count -eq 4})]
[String]$address_1,
[Parameter(Mandatory,Position = 1)]
[ValidatePattern('^(\d{1,3}\.){3}\d{1,3}$')]
[ValidateScript({[Int[]](($_.Split('.')) -le 255).Count -eq 4})]
[String]$address_2,
[Parameter(Mandatory,Position = 2)]
[ValidatePattern('^((\d{1,3}\.){3})?\d{1,3}$')]
[ValidateScript({(($_ -match '^\d+$') -and ([Int]$_ -le 255)) -or (($_.Split('.') -le 255).Count -eq 4)})]
[String]$Mask
)
Process
{
echo $address_1
echo $address_2
echo $mask
}
}
Read the documentation at the links others provided in the commnents while picking apart the code to understand how it works.
This is an example of how to use regex validation patterns to test if the two ip address and netmask are valid.
param (
[Parameter(Mandatory, Position=0)][string] $ip1,
[Parameter(Mandatory, Position=1)] [string] $ip2,
[Parameter(Mandatory, Position=2)] [string] $mask
)
# you can use [Parameter(Mandatory, Position=0)][IPAddress] $ip1 as input instead of string
# ipaddress param can accept partial ip's like 192.168 and will convert it to 192.0.0.168
# string with test would probably be better
function IsValidIPv4 ($ip) {
return ($ip -match '^(?:(?: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]?)$' -and [bool]($ip -as [ipaddress]))
}
# Validate IP's as actual IPv4
if (isValidIPv4 $ip1){
write-host "$($ip1) IS a valid IPv4 Address"
} else {
write-host "$($ip1) is not a valid IPv4 Address" -ForegroundColor Red
}
if (isValidIPv4 $ip2){
write-host "$($ip2) IS a valid IPv4 Address"
} else {
write-host "$($ip2) is not a valid IPv4 Address" -ForegroundColor Red
}
if (isValidIPv4 $mask){
write-host "$($mask) IS a valid IPv4 Address"
} else {
write-host "$($mask) is not a valid netmask" -ForegroundColor Red
}
Then check with the netmask that ip1 and ip2 are in the same network
Note :
As pointed out in my comments above
you can use [Parameter(Mandatory, Position=0)][IPAddress] $ip1 as input instead of string
ipaddress param can accept partial ip's like 192.168 and will convert it to 192.0.0.168 so this will cause incorrect validation - DON'T USE IT
I find a answer, script, with strange validation pattern:
param (
[parameter(Mandatory = $true, Position = 0)]
[Net.IPAddress]
$ip1,
[parameter(Mandatory = $true, Position = 1)]
[Net.IPAddress]
$ip2,
[parameter(Mandatory = $true, Position = 2)]
[alias("SubnetMask")]
[Net.IPAddress]
$mask
)
if (($ip1.address -band $mask.address) -eq ($ip2.address -band $mask.address)) { $true } else { $false }
Working correct:
./script.ps1 -ip1 192.168.228.110 -ip2 192.168.228.190 -mask 255.255.255.128
But when I use network prefix it always give a true.
./script.ps1 -ip1 192.168.228.110 -ip2 192.168.228.190 -mask 30
How I can modify script, to working with prefix?
I need to help with my code which is write in Powershell. Program should generate IP addresses in range. For example from 10.4.254.250 to 10.4.255.255.
When I have the same subnet (from 10.4.255.x to 10.4.255.x), all is correct. Problem starts when I have different subnet (from 10.4.254.250 to 10.4.255.255).
Output is invalid. Try it please. Thank you, for your help.
Correct output should be, that ip address which is 10.4.255.X starts from 1. Now starts from 250 to 255.
I need to get all ip addresses from variable $from to variable $to. When IP address in the same subnet $from = "10.4.255.1" $to = "10.4.255.1" all is correct. Problem starts, when different subnet $from = "10.4.254.250" $to = "10.4.255.255"
Look at my code bellow:
$from = "10.4.254.250"
$to = "10.4.255.255"
$Ip_Adresa_Od = $from -split "\."
$Ip_Adresa_Do = $to -split "\."
foreach ($Ip_Adresa_A in $Ip_Adresa_Od[0]..$Ip_Adresa_Do[0])
{
foreach ($Ip_Adresa_B in $Ip_Adresa_Od[1]..$Ip_Adresa_Do[1])
{
foreach ($Ip_Adresa_C in $Ip_Adresa_Od[2]..$Ip_Adresa_Do[2])
{
foreach ($Ip_Adresa_D in $Ip_Adresa_Od[3]..$Ip_Adresa_Do[3])
{
$Ip_Adresa_Pocitace = "$Ip_Adresa_A.$Ip_Adresa_B.$Ip_Adresa_C.$Ip_Adresa_D"
$Ip_Adresa_Pocitace
}
}
}
}
Wrong output is:
10.4.254.250
10.4.254.251
10.4.254.252
10.4.254.253
10.4.254.254
10.4.254.255
10.4.255.250
10.4.255.251
10.4.255.252
10.4.255.253
10.4.255.254
10.4.255.255
Working with IP addresses and ranges is complicated, and something I try to avoid if a program/software I am using does it already. Here are some functions that I wrote a while back that convert the addresses to decimal values, that are easier to manipulate. There are probably better, more precise solutions than this, but it will also return a range based off an address with a Subnet address or CIDR mask too. It should also cover the case #vonPryz mentioned where the addresses are across .24 CIDR ranges.
function Find-IPRange {
<#
.SYNOPSIS
Determines all the IP address in a given range or subnet.
.DESCRIPTION
This function can evaluate a set of addresses based of the following three options:
Range - What IP addresses are between this and that address
Mask - What are the IP addresses given a particular IP address and mask, i.e. 24, 25.
Subnet - What are the IP addresses given a particular IP address and subnet address, i.e 255.255.0.0, 255.255.255.192
You have to specify an IP address to use the subnet and mask options. For the range you have to specify two addresses.
.PARAMETER Start
Start address of an IP range
.PARAMETER End
End address of an IP range
.PARAMETER IP
Any valid ip address
.PARAMETER Subnet
A valid Subnet IP address i.e. 255.255.255.0, 255.255.0.0
.PARAMETER Mask
A valid net mask from 0 to 32
.EXAMPLE
Find-IPRange -IP 192.168.0.4 -mask 30
.EXAMPLE
Find-IPRange -Start 192.168.1.250 -End 192.168.2.5
.EXAMPLE
Find-IPRange -IP 10.100.100.10 -Subnet 255.255.255.240
#>
[CmdletBinding(DefaultParameterSetName = "Range")]
Param (
[Parameter(Mandatory = $true, ParameterSetName = "Range")]
[System.Net.IPAddress]
$Start,
[Parameter(Mandatory = $true, ParameterSetName = "Range")]
[System.Net.IPAddress]
$End,
[Parameter(Mandatory = $true, ParameterSetName = "Mask")]
[Parameter(Mandatory = $true, ParameterSetName = "Subnet")]
[System.Net.IPAddress]
$IP,
[Parameter(Mandatory = $true, ParameterSetName = "Subnet")]
[System.Net.IPAddress]
$Subnet,
[Parameter(Mandatory = $true, ParameterSetName = "Mask")]
[ValidateRange(0, 32)]
[System.Int32]
$Mask,
[Parameter(ParameterSetName = "Mask")]
[Parameter(ParameterSetName = "Subnet")]
[System.Management.Automation.SwitchParameter]
$ReturnRange
)
Begin {
# If the user specifies a mask, then convert it to a subnet ip address
if ($Mask) {
$Binary = ("1" * $Mask) + ("0" * (32 - $Mask))
$Decimal = [System.Convert]::ToInt64($Binary, 2)
[System.Net.IPAddress]$Subnet = ConvertFrom-IntToIP -Decimal $Decimal
}
}
Process {
# If we're looking at a subnet, we need to establish the start address and the broadcast address for it. We're using bitwise operators to do this.
if ($PSCmdlet.ParameterSetName -ne "Range") {
# Compare bits where both are a match using the bitwise AND operator
[System.Net.IPAddress]$SubnetAddr = $Subnet.Address -band $IP.Address
# Flip the subnet mask i.e. 0.0.0.255 for 255.255.255.0 by using the bitwise XOR operator and then compare against a bitwise OR operator
[System.Net.IPAddress]$Broadcast = ([System.Net.IPAddress]'255.255.255.255').Address -bxor $Subnet.Address -bor $SubnetAddr.Address
# Return the start and end of a subnet only if requested
if ($ReturnRange) { return $SubnetAddr, $Broadcast }
# Convert the start and end of the ranges to integers
$RangeStart = ConvertFrom-IPToInt -ip $SubnetAddr.IPAddressToString
$RangeEnd = ConvertFrom-IPToInt -ip $Broadcast.IPAddressToString
}
else {
$RangeStart = ConvertFrom-IPToInt -ip $Start.IPAddressToString
$RangeEnd = ConvertFrom-IPToInt -ip $End.IPAddressToString
}
# Loop through the points between the start and end of the ranges and convert them back to IP addresses
for ($Addr = $RangeStart; $Addr -le $RangeEnd; $Addr ++) { ConvertFrom-IntToIP -Decimal $Addr }
}
End {
}
}
function ConvertFrom-IPToInt {
<#
.SYNOPSIS
Converts an IP address to an Int64 value.
.DESCRIPTION
Converts an IP address to an Int64 value.
.PARAMETER IP
A valid IP address to be converted to an integer
.EXAMPLE
ConvertFrom-IPToInt -IP 192.168.0.1
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[System.Net.IPAddress]
$IP
)
Begin {
}
Process {
# Split the IP address in to octets
$Octets = $IP -split "\."
# Multiply the octets based on the maximum number of addresses each octet provides.
[System.Int64]$Decimal = ([System.Int32]$Octets[0] * [System.Math]::Pow(256, 3)) +
([System.Int32]$Octets[1] * [System.Math]::Pow(256, 2)) +
([System.Int32]$Octets[2] * 256) +
([System.Int32]$Octets[3])
}
End {
# Return the int64 value
$Decimal
}
}
function ConvertFrom-IntToIP {
<#
.SYNOPSIS
Converts an Int64 value to an IP address.
.DESCRIPTION
Converts an Int64 value to an IP address.
.PARAMETER Decimal
A decimal value for the IP Address to be converted
.EXAMPLE
ConvertFrom-IntToIP -Decimal 3232235521
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[System.Int64]
$Decimal
)
Begin {
# Initialise an array for the octets
$Octets = #()
}
Process {
# Work out first octet by dividing by the total number of addresses.
$Octets += [System.String]([System.Math]::Truncate($Decimal / [System.Math]::Pow(256, 3)))
# Work out second octet by the modulus of the first octets total number of addresses divided by the total number of address available for a class B subnet.
$Octets += [System.String]([System.Math]::Truncate(($Decimal % [System.Math]::Pow(256, 3)) / [System.Math]::Pow(256, 2)))
# Work out third octet by the modulus of the second octets total number of addresses divided by the total number of address available for a class C subnet.
$Octets += [System.String]([System.Math]::Truncate(($Decimal % [System.Math]::Pow(256, 2)) / 256))
# Work out fourth octet by the modulus of the third octets total number of addresses.
$Octets += [System.String]([System.Math]::Truncate($Decimal % 256))
# Join the strings to form the IP address
[System.Net.IPAddress]$IP = $Octets -join "."
}
End {
# Return the ip address object
$IP.IPAddressToString
}
}
DISCLAIMER: I am not a network engineer so please feel free to suggest any changes to how the addresses are converted to ints and back. This function also hasn't been through any unit testing, so there may be cases that exist where it does not work.
Example Output:
Find-IPRange -Start 10.4.254.250 -End 10.4.255.255
10.4.254.250
10.4.254.251
10.4.254.252
10.4.254.253
10.4.254.254
10.4.254.255
10.4.255.0
10.4.255.1
10.4.255.2
...truncated
10.4.255.249
10.4.255.250
10.4.255.251
10.4.255.252
10.4.255.253
10.4.255.254
10.4.255.255
Other uses:
Find-IPRange -IP 192.168.0.4 -Mask 28
192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
192.168.0.6
192.168.0.7
192.168.0.8
192.168.0.9
192.168.0.10
192.168.0.11
192.168.0.12
192.168.0.13
192.168.0.14
192.168.0.15
Find-IPRange -IP 192.168.0.4 -Subnet 255.255.255.252
192.168.0.4
192.168.0.5
192.168.0.6
192.168.0.7
You have to convert your IP address to an integer and then in each iteration of a for loop convert the integer to a byte array:
$from = "10.4.254.250"
$to = "10.4.255.255"
$Ip_Adresa_Od = $from -split "\."
$Ip_Adresa_Do = $to -split "\."
#change endianness
[array]::Reverse($Ip_Adresa_Od)
[array]::Reverse($Ip_Adresa_Do)
#convert octets to integer
$start=[bitconverter]::ToUInt32([byte[]]$Ip_Adresa_Od,0)
$end=[bitconverter]::ToUInt32([byte[]]$Ip_Adresa_Do,0)
for ($ip=$start; $ip -lt $end; $ip++)
{
#convert integer back to byte array
$get_ip=[bitconverter]::getbytes($ip)
#change endianness
[array]::Reverse($get_ip)
$new_ip=$get_ip -join "."
$new_ip
}
I hope I understand your question. I believe you would like to restart the counter on the 4th octet back to 1 once the 3rd octet iterates from 254 to 255? There's probably a better way to do this but for now hopefully this works. I've added an if statement that resets the range once the final 10.4.254.255 ip is reached. This will allow your loop to include the 10.4.255.x range starting from 1 in the 4th octet until 255 is reached. The while loop condition will be set to false once the final 10.4.255.255 IP is reached and exit.
I hope this helps and provides the desired result.
$from = "10.4.254.250"
$to = "10.4.254.255"
$Ip_Adresa_Od = $from -split "\."
$Ip_Adresa_Do = $to -split "\."
$run = "true";
while($run -eq "true")
{
if($Ip_Adresa_Pocitace -eq "10.4.254.255")
{
$from = "10.4.255.1"
$to = "10.4.255.255"
$Ip_Adresa_Od = $from -split "\."
$Ip_Adresa_Do = $to -split "\."
}
foreach ($Ip_Adresa_C in $Ip_Adresa_Od[2]..$Ip_Adresa_Do[2])
{
foreach ($Ip_Adresa_D in $Ip_Adresa_Od[3]..$Ip_Adresa_Do[3])
{
$Ip_Adresa_Pocitace = "10.4.$Ip_Adresa_C.$Ip_Adresa_D"
$Ip_Adresa_Pocitace
if($Ip_Adresa_Pocitace -eq "10.4.255.255")
{
$run = "false";
}
}
}
}
Results:
10.4.254.250
10.4.254.251
10.4.254.252
10.4.254.253
10.4.254.254
10.4.254.255
10.4.255.1
10.4.255.2
10.4.255.3
...
10.4.255.249
10.4.255.250
10.4.255.251
10.4.255.252
10.4.255.253
10.4.255.254
10.4.255.255
Solution w/ new parameters.
# Orininal Parameters
# $from = "10.4.254.250"
# $to = "10.4.254.255"
$from = "10.4.253.250"
$to = "10.4.253.255"
$Ip_Adresa_Od = $from -split "\."
$Ip_Adresa_Do = $to -split "\."
$run = "true";
while($run -eq "true")
{
if($Ip_Adresa_Pocitace -eq "10.4.253.255")
{
# Orininal Parameters
# $from = "10.4.255.1"
# $to = "10.4.255.255"
$from = "10.4.254.1"
$to = "10.4.254.255"
$end = $to
$Ip_Adresa_Od = $from -split "\."
$Ip_Adresa_Do = $to -split "\."
}
foreach ($Ip_Adresa_C in $Ip_Adresa_Od[2]..$Ip_Adresa_Do[2])
{
foreach ($Ip_Adresa_D in $Ip_Adresa_Od[3]..$Ip_Adresa_Do[3])
{
$Ip_Adresa_Pocitace = "10.4.$Ip_Adresa_C.$Ip_Adresa_D"
$Ip_Adresa_Pocitace
if($Ip_Adresa_Pocitace -eq $end)
{
$run = "false";
}
}
}
}
Results:
10.4.253.250
10.4.253.251
10.4.253.252
10.4.253.253
10.4.253.254
10.4.253.255
10.4.254.1
10.4.254.2
10.4.254.3
...
10.4.254.253
10.4.254.254
10.4.254.255
If the free space of a drive is 100% free and I set the minimum threshold space to 25%, the script incorrect reports that the drive is below threshold.. meaning 100 < 25
Although If I were to replace
$FreePercent = "{0:N0}" -f (100 * $objDisk.FreeSpace/$objDisk.Size) with
$FreePercent = (100 * $objDisk.FreeSpace/$objDisk.Size) ...
I get correct results.
How do i fix the rounding off problem.
Here is my code
# For Loop - get % free space of all drives
#Define Variables
$Notify = 0
$MinFreePercent = "25"
#$FileDriveSpace = "c:\temp\DriveSpace.txt"
$ComputerName = $(Get-WmiObject Win32_Computersystem).name
$OutArray = #()
$outarray += "Disk space Alerts and Utilizations on server $ComputerName"
$AllDisks = get-wmiobject Win32_LogicalDisk -Filter “DriveType = 3"
#Omit the a, b drives if exist
$AllDisks = $AllDisks | ? { $_.DeviceID -notmatch "[ab]:"}
foreach ($objdisk in $AllDisks)
{
#$FreePercent = "{0:P0} " -f ($objDisk.FreeSpace/$objDisk.Size)
$FreePercent = "{0:N0}" -f (100 * $objDisk.FreeSpace/$objDisk.Size)
If ($FreePercent -lt $MinFreePercent)
{
$Threshold = "Threshold Reached"
$Notify = 1
}
Else
{ $Threshold = "N/A"}
$DeviceId = $objDisk.DeviceID
$myobj = "" | Select "Drive","PercentFreeSpace", "Threshold"
$myobj.Drive = $DeviceId
$myobj.PercentFreeSpace = $FreePercent
$myobj.Threshold = $Threshold
$outLine = $DeviceId + " " + $FreePercent + " " + $Threshold + " " + $MinFreePercent
$outLine
#Add the object to the out-array
$outarray += $myobj
#Wipe the object just to be sure
$myobj = $null
}
So the problem here is the -f or formatting operator. It's taking your awesome drive percent free [int] and turning it into a plain old boring [string]. I personally use the [math] accelerator and call the round method.
[math]::Round($mynumber,0)
You could also save yourself some time by looking in the technet gallery for this type of thing:
http://gallery.technet.microsoft.com/Get-HardDrive-0eef638f
I don't remember if that version returns data as a string or an integer but you'll see an example of the round method in action.
For example, given a list 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8 and a number 4, it returns a list of list with length of 4, that is
(1, 2, 3, 4), (5, 6, 7, 8), (1, 2, 3, 4), (5, 6, 7, 8).
Basically I want to implement the following Python code in Powershell.
s = 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8
z = zip(*[iter(s)]*4) # Here N is 4
# z is (1, 2, 3, 4), (5, 6, 7, 8), (1, 2, 3, 4), (5, 6, 7, 8)
The following script returns 17 instead of 5.
$a = 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,0
$b = 0..($a.Length / 4) | % { #($a[($_*4)..($_*4 + 4 - 1)]) }
$b.Length
This is a bit old, but I figured I'd throw in the method I use for splitting an array into chunks. You can use Group-Object with a constructed property:
$bigList = 1..1000
$counter = [pscustomobject] #{ Value = 0 }
$groupSize = 100
$groups = $bigList | Group-Object -Property { [math]::Floor($counter.Value++ / $groupSize) }
$groups will be a collection of GroupInfo objects; in this case, each group will have exactly 100 elements (accessible as $groups[0].Group, $groups[1].Group, and so on.) I use an object property for the counter to avoid scoping issues inside the -Property script block, since a simple $i++ doesn't write back to the original variable. Alternatively, you can use $script:counter = 0 and $script:counter++ and get the same effect without a custom object.
Wrote this in 2009 PowerShell Split-Every Function
Probably can be improved.
Function Split-Every($list, $count=4) {
$aggregateList = #()
$blocks = [Math]::Floor($list.Count / $count)
$leftOver = $list.Count % $count
for($i=0; $i -lt $blocks; $i++) {
$end = $count * ($i + 1) - 1
$aggregateList += #(,$list[$start..$end])
$start = $end + 1
}
if($leftOver -gt 0) {
$aggregateList += #(,$list[$start..($end+$leftOver)])
}
$aggregateList
}
$s = 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8
$r = Split-Every $s 4
$r[0]
""
$r[1]
""
$r[2]
""
$r[3]
PS> $a = 1..16
PS> $z=for($i=0; $i -lt $a.length; $i+=4){ ,($a[$i]..$a[$i+3])}
PS> $z.count
4
PS> $z[0]
1
2
3
4
PS> $z[1]
5
6
7
8
PS> $z[2]
9
10
11
12
PS> $z[3]
13
14
15
16
Providing a solution using select. It doesn't need to worry whether $list.Count can be divided by $chunkSize.
function DivideList {
param(
[object[]]$list,
[int]$chunkSize
)
for ($i = 0; $i -lt $list.Count; $i += $chunkSize) {
, ($list | select -Skip $i -First $chunkSize)
}
}
DivideList -list #(1..17) -chunkSize 4 | foreach { $_ -join ',' }
Output:
1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16
17
#Shay Levy Answer: if you change the value of a to 1..15 then your solution not working anymore ( Peter Reavy comment )
So this worked for me:
$a = 1..15
$z=for($i=0; $i -lt $a.length; $i+=4){if ($a.length -gt ($i+3)) { ,($a[$i]..$a[$i+3])} else { ,($a[$i]..$a[-1])}}
$z.count
$a = 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,0
$b = 0..([Math]::ceiling($a.Length / 4) - 1) |
% { #(, $a[($_*4)..($_*4 + 4 - 1)]) }
Don't know why I had to put a comma after (.
Clear-Host
$s = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18
$count = $s.Length
$split = $count/2
$split --
$b = $s[0..$split]
$split ++
$a = $s[$split..$count]
write-host "first array"
$b
write-host "next array"
$a
#clean up
Get-Variable -Exclude PWD,*Preference | Remove-Variable -EA 0