Cannot set a string as a key for my hashtable - powershell

I'm trying to set this string as my key:
a -long " string that - has. double and single quotes and dashes and dots
This string is the product of String Builder ToString() method.
The Hashtable is initialized like this: $myHashtable = #{ }
This is the error: Cannot convert value "stringAbove" to type "System.Int32". Error: "Input string was not in a correct format."
I tried escaping the double quotation marks with a backtick. But got still the same error.
$resultFromToString = $myBuilder.ToString()
$myHashtable[$resultFromToString] = #{
One = $one;
Two = $two;
}

The error message implies that $myHashtable contains an array, not a hashtable.
To determine the actual type of $myHashtable, execute $myHashtable.GetType() or Get-Member -InputObject $myHashtable
This example shows that there's no problem with your string, given that a string with any value - even '' - can serve as a hashtable key:
$myHashtable = #{} # Initialize.
$myHashtable['a - long string that has " and '' quotes and - and .'] = 'foo'
$myHashtable # Output
Output:
Name Value
---- -----
a - long string that has " an… foo
As for what you tried:
By contrast, if $myHashtable is an array (irrespective of the type of its elements), your symptom surfaces, with any string value (that can't be converted to an integer), given that only integers can serve as array indices:
$myHashtable = #{}, #{} # !! ARRRAY (of hashtables)
$myHashtable['some key'] = 'foo' # !! FAILS
Error output:
Cannot convert value "some key" to type "System.Int32". Error: "Input string was not in a correct format."
Note that, as the error message hints at, PowerShell automatically tries to convert a string index to an integer, so that something like the following does work, perhaps surprisingly:
# Same as:
# $myHashtable[0] = 'foo'
# because PowerShell automatically converts to [int]
$myHashtable[' -0 '] = 'foo'

Related

Pass string value having space to another powershell file

I have a powershell script which calls another powershell file passing a string argument.
param (
[string]$strVal = "Hello World"
)
$params = #{
message = "$strVal"
}
$sb = [scriptblock]::create(".{$(get-content $ps1file -Raw)} $(&{$args} #params)")
Somehow the script passes message variable without double quotes so the powershell file receives only the first part of the message variable (before space) i.e. "Hello".
How can I pass the strVal variable with space (i.e. "Hello World")?
A double quote pair signals PowerShell to perform string expansion. If you want double quotes to output literally, you need to escape them (prevent expansion) or surround them with single quotes. However, a single quote pair signals PowerShell to treat everything inside literally so your variables will not interpolate. Given the situation, you want string expansion, variable interpolation, and literal double quotes.
You can do the following:
# Double Double Quote Escape
#{message = """$strVal"""}
Name Value
---- -----
message "Hello World"
# Backtick Escape
#{message = "`"$strVal`""}
Name Value
---- -----
message "Hello World"
Quote resolution works from left to right, which means the leftmost quote type takes precedence. So '"$strVal"' will just print everything literally due to the outside single quote pair. "'$strVal'" will print single quotes and the value of $strVal.

Getting the binary value of a character string in 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.

PowerShell datatype conversion from user specified string value to array is not resulting correct result

When I convert the variable value which is in string to an array format, it converted data type to an array but the result is not an array.
Example:
cls
#Actual String value concatenated with dot (.)
$EmpInfo="Name.Address.Pincode.Phone"
Write-Host $EmpInfo
#Change string value to array format
$EmpInfoArray= '"'+$EmpInfo.Replace('.',""",""")+'"'
Write-Host $EmpInfoArray
$EmpInfoArray.gettype()
#Convert BaseType value from 'system.object' to 'system.array'
[Array]$ConvertedArray = $EmpInfoArray
$ConvertedArray.GetType()
Write-Host $ConvertedArray.Count
Write-Host $ConvertedArray[0]
Result:
1
"Name","Address","Pincode","Phone"
It is not resulting the value as an array. If it is an array then the result would be array count 4 and first array value 'Name'
Do we have any workaround to result the converted user specified string value to an array.
Split your EmpInfoArray with ','
[Array]$ConvertedArray = $EmpInfoArray -split ','
Invoke-expression fixed this issue. Now it is resulting as an array.
cls
#Actual String value concatenated with dot (.)
$EmpInfo="Name.Address.Pincode.Phone"
Write-Host $EmpInfo
#Change string value to array format
$EmpInfoArray = invoke-expression ('"'+$EmpInfo.Replace('.',""",""")+'"')
$EmpInfoArray.gettype()
$EmpInfoArray.count
$EmpInfoArray[0]
Result:
4
Name

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))