I am trying to convert number into IP address using powershell method and checking same online, I am getting 2 different result.
Example:
number = 16812043
result1 = 11.136.0.1 #using powershell
result2 = 1.0.136.11 #https://codebeautify.org/decimal-to-ip-converter
I have tried below code
function Convert-NumberToIP
{
param(
[Parameter(Mandatory=$true)][string]$number
)
[Int64] $numberInt = 0
if([Int64]::TryParse($number, [ref]$numberInt))
{
if(($numberInt -ge 0) -and ($numberInt -le 0xFFFFFFFFl))
{
([IPAddress] $numberInt).ToString()
}
}
}
Convert-NumberToIP -number 16812043
I am getting 2 different result not sure which 1 is correct, or should I update the function.
Use the IPAddress.NetworkToHostOrder() method to flip the endianness of the octets represented by your decimal number:
PS ~> [ipaddress]::new([ipaddress]::NetworkToHostOrder(16812043)).IPAddressToString
1.0.136.11
Related
I am trying to build an array of possible IP addresses based on a user's input. i.e. IP address along with a CIDR number. My end goal is to compare this list with a separate list of addresses and find which are is missing.
Example
user input: 192.168.1.0 /24
I want to build an array for all possible values for the /24 network (i.e. the IP address can be anywhere from 192.168.1.0 - 192.168.1.255)
In order for this to work, I think I have to convert the IP address to binary and then find the bits that will be the host part of the network, which I've done here:
function ConvertToBinary{
param($ipAddress)
[string]$binaryIP = -join ($ipAddress.Split('.') | ForEach-Object {[System.Convert]::ToString($_,2).PadLeft(8,'0')})
return $binaryIP
}
function FindHost{
param(
[string]$binaryIPAddress,
[int32]$CIDR
)
$hostBits = 32-$CIDR
[string]$myHost = $binaryIPAddress.Substring($binaryIPAddress.Length-$hostBits)
return $myHost
}
$myip = ConvertToBinary "192.168.3.1"
$myHost = FindHost $myip 8
I'm a little stuck on how to proceed, so if anyone can help me out or point me in the right direction, it would be much appreciated
I wrote this using some similar questions to get the first and last address for any subnet given a random IP and mask:
Function Get-SubnetAddresses {
Param ([IPAddress]$IP,[ValidateRange(0, 32)][int]$maskbits)
# Convert the mask to type [IPAddress]:
$mask = ([Math]::Pow(2, $MaskBits) - 1) * [Math]::Pow(2, (32 - $MaskBits))
$maskbytes = [BitConverter]::GetBytes([UInt32] $mask)
$DottedMask = [IPAddress]((3..0 | ForEach-Object { [String] $maskbytes[$_] }) -join '.')
# bitwise AND them together, and you've got the subnet ID
$lower = [IPAddress] ( $ip.Address -band $DottedMask.Address )
# We can do a similar operation for the broadcast address
# subnet mask bytes need to be inverted and reversed before adding
$LowerBytes = [BitConverter]::GetBytes([UInt32] $lower.Address)
[IPAddress]$upper = (0..3 | %{$LowerBytes[$_] + ($maskbytes[(3-$_)] -bxor 255)}) -join '.'
# Make an object for use elsewhere
Return [pscustomobject][ordered]#{
Lower=$lower
Upper=$upper
}
}
Usage looks like:
Get-IPAddresses 10.43.120.8 22
Lower Upper
----- -----
10.43.120.0 10.43.123.255
And I put this together to generate the whole list. I'm sure this could be done better, but the simple instructions run fast enough:
Function Get-IPRange {
param (
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName)][IPAddress]$lower,
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName)][IPAddress]$upper
)
# use lists for speed
$IPList = [Collections.ArrayList]::new()
$null = $IPList.Add($lower)
$i = $lower
# increment ip until reaching $upper in range
while ( $i -ne $upper ) {
# IP octet values are built back-to-front, so reverse the octet order
$iBytes = [BitConverter]::GetBytes([UInt32] $i.Address)
[Array]::Reverse($iBytes)
# Then we can +1 the int value and reverse again
$nextBytes = [BitConverter]::GetBytes([UInt32]([bitconverter]::ToUInt32($iBytes,0) +1))
[Array]::Reverse($nextBytes)
# Convert to IP and add to list
$i = [IPAddress]$nextBytes
$null = $IPList.Add($i)
}
return $IPList
}
Converting to [IPAddress] on the last line is nice for validating all the results are real, but probably not necessary if you just want the ipv4 strings. Usage:
Get-SubnetAddresses 10.43.120.8 30 | Get-IPRange | Select -ExpandProperty IPAddressToString
10.43.120.8
10.43.120.9
10.43.120.10
10.43.120.11
Sources:
https://stackoverflow.com/a/51307519/7411885
https://stackoverflow.com/a/58821442/7411885
I'm trying to put in default/null/missing values for .printout in PowerPoint but I can't get it to work. The value's that are giving me troubles are defined as integers in this page.
Usually I have been able to use [System.Type]::Missing or '' but neither of those work and I get the following:
Cannot convert the "System.Reflection.Missing" value of type "System.Reflection.Missing" to type "System.Int32".
How can I put in null values for those two params of .printout for PowerPoint?
Here is what I have for code so far:
###PPT
IF ($FILETYPE -eq "PPT") {
ECHO "PPT_FOUND"
$msoFalse = [Microsoft.Office.Core.MsoTriState]::msoFalse
$msoTrue = [Microsoft.Office.Core.MsoTriState]::msoTrue
$ObjPPT = New-Object -comobject PowerPoint.Application
$ObjPPT.Visible = $msoTrue
#$ObjPPT.DisplayAlerts = $msoFalse
#Exception setting "DisplayAlerts": "Cannot convert value "msoFalse" to type "Microsoft.Office.Interop.PowerPoint.PpAlertLevel" due to enumeration values that are not valid. Specify one of the following
#enumeration values and try again. The possible enumeration values are "ppAlertsNone,ppAlertsAll"."
#.Open
$FILENAME = $FILEPATH
IF (!$ReadOnly){$ReadOnly = $msoTrue}
IF (!$Untitled){$Untitled = $missing}
IF ((!$WithWindow) -and ($OPENUI -eq "FALSE")){$WithWindow = $msoFalse} ELSE {$WithWindow = $msoTrue}
$ObjPresentation=$ObjPPT.Presentations.open($FILENAME,$ReadOnly,$Untitled,$WithWindow)
#.Print
#.PrintOut (From[Integer], To[Integer], PrintToFile[String], Copies [Integer], Collate[Bool]{msoTrue/False})
IF (!$From){[int]$From = $missing}
IF (!$To){[int]$To = $missing}
IF (!$PrintToFile){[string]$PrintToFile = $missing}
#Copies Defined Earlier
IF (!$Collate){$Collate = $msoTrue}
#$ObjPresentation.printout($From,$To,$PrintToFile,$COPIES,$Collate)
$ObjPresentation.printout($From,$To)# , ,$COPIES,$Collate)
#All Done
Sleep 2
$ObjPresentation.Close()
$ObjPPT.Quit()
Do-CloseIfRunning -Process $PROCESS
}
[gc]::collect()
[gc]::WaitForPendingFinalizers()
#Get-Variable
#PAUSE
Turns out using 0 caused an error, but using -1 for From/To values worked as expected (null values).
In AWS each instance has an ID that looks something like this: i-1234567890abcdef ; the last 16 characters being a hexadecimal number. I would like to treat the "1234567890abcdef" part as a hex number and convert it to base36, so a-z0-9. This way I can use is as the computer's name and not go over the 15 character limit. How is that done in Powershell ?
Converting the input from hex is easy enough: skip the first two characters, and convert to UInt64:
[convert]::ToUInt64($text.Substring(2), 16)
but PowerShell (.Net) has no built-in way to convert to base 36. You'll need to implement it yourself, e.g. this code taken from https://ss64.com/ps/syntax-base36.html and adjusted for larger numbers:
function convertTo-Base36
{
[CmdletBinding()]
param (
[parameter(valuefrompipeline=$true, HelpMessage="Integer number to convert")]
[uint64]$DecimalNumber=""
)
$alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
do
{
$remainder = ($DecimalNumber % 36)
$char = $alphabet.Substring($remainder, 1)
$base36Num = "$char$base36Num"
$DecimalNumber = ($DecimalNumber - $remainder) / 36
}
while ($DecimalNumber -gt 0)
$base36Num
}
Then:
$x='i-1234567890abcdef'
$hexPart = $x.Substring(2)
$decimal = [convert]::ToUInt64($hexPart, 16)
convertTo-Base36 $decimal
# -> 9YS742MX86WF
or:
[convert]::ToUInt64('i-1234567890abcdef'.Substring(2), 16) | Convertto-Base36
not sure how to convert a string to an integer and then do an "add 1" to it. Here's what I'm trying to do:
1) Capture an IP address from a prompt
2) create list of variables with the increasing IPs as such:
$startIP = Read-Host
$ip1 = $startIP
$ip2 = $ip1 + 1
$ip3 = $ip2 + 1
So for example, we'd input 10.0.0.1, and then $ip2 would be 10.0.0.2 and so on.
I know I need to convert this to an integer after reading the input, but am unsure how to do that. Many thanks!
Found these functions that converts an IP to an Int64 and back
Function Convert-IpToInt64 () {
param ([String]$ip)
process {
$octets = $ip.split(".")
return [int64]([int64]$octets[0]*16777216 +[int64]$octets[1]*65536 +[int64]$octets[2]*256 +[int64]$octets[3])
}
}
Function Convert-Int64ToIp() {
param ([int64]$int)
process {
return (([math]::truncate($int/16777216)).tostring()+"."+([math]::truncate(($int%16777216)/65536)).tostring()+"."+([math]::truncate(($int%65536)/256)).tostring()+"."+([math]::truncate($int%256)).tostring() )
}
}
With that you can now convert the input to an something that can be incremented
$startIP = Read-Host
$ip1 = Convert-IpToInt64 $startIP
$ip2 = $ip1 + 1
$ip3 = $ip2 + 1
I need a method which returns the standard deviation of the last access time in a folder. Here is the code:
function standardDeviation {
Param(
[Parameter(Mandatory=$true)]
[String]$tPath
)
$moy = moyAge $tPath
$variance = 0
$nbFiles = 1
dir | ForEach-Object {
if (!($_.PsIsContainer)) {
$nbDays = $_.LastAccessTime
$nbDays = $nbDays.Days
$sq = $nbDays - $moy
$sq = $sq*$sq
$variance += $sq
$nbFiles++
}
}
$variance = $variance / $nbFiles
$variance = [math]::sqrt($variance)
}
I don't know why, but it always returns 0. Does someone know why?
(moyAge works, and returns an int (number of days))
Your function doesn't actually return anything, so any call will "return" $null. Either change
$variance = [math]::sqrt($variance)
to
[math]::sqrt($variance)
or add a line
$variance
or
return $variance
at the end of the function.
Also, as #MathiasRJessen pointed out, DateTime objects don't have a Days property. If you want the difference in days between today and a specific date you need to calculate a timespan first:
$nbDays = ((Get-Date).Date - $_.LastAccessTime.Date).Days