Convert string value "$false" to boolean variable - powershell

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

Related

Cannot set a string as a key for my hashtable

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'

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

Concatenate elements of a char array and strings in powershell

I'm probably over thinking this, but this is not coming out the way I expect. I've searched google, I've searched stackoverflow. Please Help.
Here are some variables for testing, and the invocation of a function:
$SQL_FirstName = "PowerShell";
$SQL_LastName = "CreateUser";
$SQL_Office = "TEST";
$SQL_IsAdmin = $true;
Create_User($SQL_FirstName.ToLower(), $SQL_LastName.ToLower(), $SQL_Office, $SQL_IsAdmin);
Here is the function, not much there yet:
Function Create_User([string]$FirstName, [string]$LastName, $Office, $IsAdmin)
{
$FirstNameCharArray = [char[]]$FirstName;
$UserName = [string]$FirstNameCharArray[0] + $LastName;
Write-Host $UserName;
}
Now I expect the output to be "pcreateuser". But it's not. I have tried casting different things, I have tried surrounding my variables with $(). I have tried using the + symbol and not using the + symbol. I have tried smashing the variables right up against each other. Every single time it just outputs "p".
Any help would be appreciated. Thanks!
It's because of how you are calling the function. You are not supposed to use brackets for function calls nor use commas to separate the parameters (unless you are sending array values on purpose or subexpressions). You have passed it a single array of those elements.
Create_User $SQL_FirstName.ToLower() $SQL_LastName.ToLower() $SQL_Office $SQL_IsAdmin
In your function call your sent an array to $firstname which was casted as a string "powershell createuser TEST True". The other parameters would have been blank. Hence your output.
They work just the same as cmdlet calls. Just use spaces to separate the parameters and their values.
Get-ChildItem -Filter "*.txt" -Path "C:\temp"
String to char array
For what it is worth you don't need to cast the string as a char array. You can just use array notation directly on the string.
PS C:\Users\Matt> [string]"Bagels"[0]
B
Heck you don't even need to cast it "Bagels"[0]

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