Getting the binary value of a character string in Powershell - powershell

$getInput = Read-Host "ASCII or Binary? `n"
$getInput = $getInput.toLower()
if($getInput -eq "ascii"){
""
#Write-Host "Type In Your ASCII" -backgroundcolor "black"
$getAscii = Read-Host "Type In Your ASCII`n"
""
""
$readAscii = #($getAscii)
[byte[]]$outBytes = $readAscii
}
elseif($getInput -eq "binary"){
}
else{
Write-Host "Wrong Input... [ASCII] or [BINARY]" -backgroundcolor "red" -foregroundcolor "white"
}
I want to be able to get a users paragraph or whatever string they put in and convert it to binary. The [conver]::toString($getAscii,2) only works for integers.

Try this
$string = "ABCDEF"
[system.Text.Encoding]::Default.GetBytes($String) | %{[System.Convert]::ToString($_,2).PadLeft(8,'0') }
[system.Text.Encoding]::Default.GetBytes($String)
This turns a string into a byte array. You can change Default to another Encoding
| %{[System.Convert]::ToString($_,2).PadLeft(8,'0') }
This turns each byte in the byte array into a binary representation.
ToString([object],[Enum]), in this case the byte will have a number value like 65 if converted to string the 2 will say turn the 65 into base 2. You could also use 8(octo), 10(which is the same as none aka base 10) and 16(Hex). Then it pads the left till its 8 char long with char 0's

'hello world' -split '' | % {
if ($_ -ne '') {
#[int][char]$_
[System.Convert]::ToString(([int][char]$_),2)
}
}
Use the split operator to split the string by each character
Send that down the pipeline to a foreach-object loop
The split operation ends up including the space character in the string
so the conditional makes sure we don't act upon it--we filter it out.
The commented line was for testing purposes. Each character has a
TYPE of [string] and we need it as a [char] so we explicitly cast it
as such and the PowerShell engine dynamically switches it for us (as
long as it can). In the same line, we explicitly cast the [char] to
an [int] to get the ASCII->decimal representation. This test was just to
ensure I was getting the right output and I left it commented in
case the OP wanted to see it.
Finally, we use the ToString() method of the System.Convert class which accepts a "base"
parameter to define that we want a base2 (binary) representation of
the integer supplied in position 1, casted as TYPE [string].

I recommend utilizing the Encoding library similarly to this user:
$stringToConvert = "Hello World"
$test = [System.Text.Encoding]::UTF8.GetBytes($stringToConvert) | %{ [System.Convert]::ToString($_,2).PadLeft(8,'0') }
$test
Source: https://www.reddit.com/r/PowerShell/comments/3e82vk/convert_string_to_binary_and_back/
*Note: I believe the original poster of this method intended to assign $foo to the second conversion. I believe it will work either way because the return will be dumped to the variable below.

Related

How to add multiple values to case sensitive powershell hashtable?

I need a (key,value) hashtable of alphabet to convert letters and numbers to codes in PowerShell, i did it like this:
$symbols = #{"A"="0x41"; "B"="0x42"; "C"="0x43"; "D"="0x44"; "E"="0x45"; "F"="0x46"; "G"="0x47"; "H"="0x48"; "I"="0x49"; ....}
But then i noticed that hashtables are case insensitive by default, and i need case sensitivity. I found that i can create case sensitive hashtable with:
$symbols = New-Object System.Collections.Hashtable
and then add values:
$symbols.Add("a","0x41")
$symbols.Add("A","shift+0x41")
....
But that will take 52 lines of code, is there any way to add multiple values to CASE SENSITIVE hashtable in one line?
Because if i try to combine two hashtables or add values in one line, it becomes case INsensitive and throws error about duplicate values.
I think this potentially does what you're after:
$symbols = New-Object System.Collections.Hashtable
((65..90) + (97..122)) | ForEach-Object {
$symbols.Add([char]$_,"$(if ($_ -lt 97) {'shift+'})0x{0:x}" -f $( if ($_ -lt 97) { $_ } Else { $_ -32 }))
}
$symbols.GetEnumerator() | sort name
This assumes that you're converting the character to hex code.
Explanation:
((65..90) + (97..122)) creates an array of two ranges of numbers, which are the decimal codes for A..Z and a..z.
Converts the decimal code to it's corresponding character letter with [Char]
If the code is less than 97 add the text Shift+ to the start of the value.
Uses "0x{0:x}" -f <number> to convert the number to its hex equivalent, changing the range back to the lower case range for the uppercase characters by subtracting 32.

Powershell - remove currency formatting from a number

can you please tell me how to remove currency formatting from a variable (which is probably treated as a string).
How do I strip out currency formatting from a variable and convert it to a true number?
Thank you.
example
PS C:\Users\abc> $a=($464.00)
PS C:\Users\abc> "{0:N2}" -f $a
<- returns blank
However
PS C:\Users\abc> $a=-464
PS C:\Users\abc> "{0:C2}" -f $a
($464.00) <- this works
PowerShell, the programming language, does not "know" what money or currency is - everything PowerShell sees is a variable name ($464) and a property reference (.00) that doesn't exist, so $a ends up with no value.
If you have a string in the form: $00.00, what you can do programmatically is:
# Here is my currency amount
$mySalary = '$500.45'
# Remove anything that's not either a dot (`.`), a digit, or parentheses:
$mySalary = $mySalary -replace '[^\d\.\(\)]'
# Check if input string has parentheses around it
if($mySalary -match '^\(.*\)$')
{
# remove the parentheses and add a `-` instead
$mySalary = '-' + $mySalary.Trim('()')
}
So far so good, now we have the string 500.45 (or -500.45 if input was ($500.45)).
Now, there's a couple of things you can do to convert a string to a numerical type.
You could explicitly convert it to a [double] with the Parse() method:
$mySalaryNumber = [double]::Parse($mySalary)
Or you could rely on PowerShell performing an implicit conversion to an appropriate numerical type with a unary +:
$mySalaryNumber = +$mySalary

Convert string value "$false" to boolean variable

Reason I'm Doing This
I'm trying to set a token in a file I have. The contents of the token is 1 line in the file, and it's string value is $token=$false
Simplified to test code
When I try to convert this token into a bool value, I'm having some problems. So I wrote test code and found I'm not able to convert the string to a bool value.
[String]$strValue = "$false"
[Bool]$boolValue = $strValue
Write-Host '$boolValue =' $boolValue
This gives the following error...
Cannot convert value "System.String" to type "System.Boolean", parameters of this type only accept booleans or numbers, use $true, $false, 1 or 0 instead.
At :line:2 char:17
+ [Bool]$boolValue <<<< = $strValue
As you can see, I am using the $false value as is suggested by the error message, but it's not accepting it. Any ideas?
In PowerShell, the usual escape character is the backtick. Normal strings are interpolated: the $ symbol is understood and parsed by PowerShell. You need to escape the $ to prevent interpolation. This should work for you:
[String]$strValue = "`$false"
To convert "$true" or "$false" to a boolean in a generic way, you must first drop the leading $:
$strValue = $strValue.Substring(1)
Then convert to boolean:
[Boolean]$boolValue = [System.Convert]::ToBoolean($strValue)
Using your code from your comment, the shortest solution would be:
$AD_Export_TokenFromConfigFile =
[System.Convert]::ToBoolean(Get-Content $AD_Export_ConfigFile
| % {
If($_ -match "SearchUsersInfoInAD_ConfigToken=") {
($_ -replace '*SearchUsersInfoInAD_ConfigToken*=','').Trim()
}
}.Substring(1))

In powershell is there a way to check if a user's input has a decimal in it?

I am writing a code and a part of it asks the user inputs a number and I have to check if the number is a decimal. If the number is a decimal than output has to say "this is a decimal number" and if the number is not a decimal than the output says "This is not a decimal number". Is there a way to do this?
Since the cat is out of the bag now you could just attempt to cast the value to a [decimal]. If successful return $true
function IsDecimal($value){
Try{
[decimal]$value | Out-Null
$true
} Catch {
$false
}
}
IsDecimal "10"
IsDecimal "1.2"
IsDecimal "bagels"
output
True
True
False
So you could use this in other parts of your code if need be
If(IsDecimal $string){Write-Host "Stuff"}
You can read more about casting in from this question. Lots of good answers here that don't need to be repeated.
In that regard
If($value -as [decimal]){Write-Host "Valid decimal"}else{Write-Host "Not valid decimal"}
I believe if you are trying to pass number from command line and checking then it would look something like below.
PS C:\> .\Untitled1.ps1 123
Does not contains '.'
PS C:\> .\Untitled1.ps1 123.24
Contains '.'
Untitled1.ps1
============
if ($args[0].GetType() -eq [System.Double])
{
Write-Host "Contains '.'";
}
else
{
Write-Host "Does not contains '.'";
}
Your question can work two ways. You are looking to determine is a number is a decimal. Eiter you mean the type or you mean if the number has decimals.
Lets work with variable $Sum and $Sum holds the value 2.5
In case you want to know the type you could just enter:
$sum.GetType().Name
In case you want a true or false you could enter:
if (($sum - ($sum -as [int])) -ne 0) {"$false"}Else {$True}
You see, by casting $Sum as an [int] it would automatically be rounded (in this case to 2). So by extracting ($Sum -as [int]) from $Sum you would end up with an outcome of 2.5-2 = 0.5 which means that sum must be anything else but a rounded number.

PowerShell: How to limit string to N characters?

substring complains when I try to limit a string to 10 characters which is not 10 or more characters in length. I know I can test the length but I would like to know if there is a single cmdlet which will do what I need.
PS C:\> "12345".substring(0,5)
12345
PS C:\> "12345".substring(0,10)
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string.
Parameter name: length"
At line:1 char:18
+ "12345".substring( <<<< 0,10)
Do you need exactly a cmdlet? I wonder why you don't like getting length. If it's part of a script, then it looks fine.
$s = "12345"
$s.substring(0, [System.Math]::Min(10, $s.Length))
Using the substring function has it's limitations and requires you to first capture the length of the string. Granted this does work you can do it without that limitation.
The following will return the first 5 characters of the string
"1234567890"[0..4] -join "" # returns the string '12345'
And this will work on strings that are shorter than desired length
"1234567890"[0..1000] -join "" # returns the string '1234567890'
You can load and use other libraries and use their string functions, for example the visual
basic string functions work nicely for what you want to do
call once per session
>[void][reflection.assembly]::LoadWithPartialName("microsoft.visualbasic")
then use various vb string functions
>[microsoft.visualbasic.strings]::left("12345",10)
12345
or
>[microsoft.visualbasic.strings]::mid("12345",1,10)
12345
The previous answers didn't suit my purposes (no offence!) so I took Denomales suggestion above and rolled it into a function which I thought I'd share:
function Trim-Length {
param (
[parameter(Mandatory=$True,ValueFromPipeline=$True)] [string] $Str
, [parameter(Mandatory=$True,Position=1)] [int] $Length
)
$Str[0..($Length-1)] -join ""
}
Example usages:
"1234567" | Trim-Length 4 # returns: "1234"
"1234" | Trim-Length 99 # returns: "1234"
Thanks to Dmitry for the answer, I turned it into a function and made it so it is 1 based as opposed to 0 based.
function acme-substr ([string]$str, $start, $end) {
$str.substring($start-1, [System.Math]::Min($str.Length-1, $end))
}
> $foo="0"*20
> $foo
00000000000000000000
> acme-substr $foo 1 5
00000