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
Related
I have a string,
$string = "2,55"
How to convert this string to decimal?
In short -
[decimal]$string.Replace(",", ".")
Another way of converting this (not necessarily better) is using the ToDecimal method with a specific culture. Here I'm using the standard french culture.
[System.Convert]::ToDecimal("2,55",[cultureinfo]::GetCultureInfo('fr-FR'))
2.55
You should convert using the current locale. Replacing , with . isn't reliable and is slightly slower (because another string must be created). Both Parse and TryParse have a culture parameter that you can use
PS D:\> $string = "2,55"
PS D:\> $culture = Get-Culture
PS D:\> [decimal]::Parse($string, $culture)
2.55
PS D:\> [decimal]$dec = 0
PS D:\> [decimal]::TryParse($string, [Globalization.NumberStyles]::Float, $culture, [ref]$dec)
True
PS D:\> $dec
2.55
If you know the locale of the input then parse directly in that locale by using GetCultureInfo
$culture = [cultureinfo]::GetCultureInfo('fr-FR')
Note that if the string contains the exponent like "2,55e2" then none of the current answers actually work (although it may appears to work). For more details read How can I convert a string such as 5.7303333333e+02 to decimal in PowerShell?
To force a conversion to a specific datatype, prefix the value or variable with the type in square brackets, this is known as a Cast Operator and forces the chosen datatype:
$string = "100.5"
$decimal = [decimal]$string
$string + 0.5
# Outputs 100.10.5
$decimal + 0.5
# Outputs 101,0
More information can be found here
$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.
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
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))
I'm looking for example of how I would solve the scenario below:
Imagine my printer has the following property for "Status"
0 -Offline
2 -Paper Tray Empty
4 -Toner Exhausted
8 -Paper Jam
When I query status it returns a value of 12. I can obviously see that this means the printer has the Toner Exhausted and a Paper Jam, but how would I work this out with Powershell?
Thanks
The boolean bitwise and operator in Powershell is -band.
Assume you define your values and descriptions in a hashtable, and have the value of 12 from the printer:
$status = #{1 = "Offline" ; 2 = "Paper Tray Empty" ; 4 = "Toner Exhausted" ; 8 = "Paper Jam" }
$value = 12
Then, this statement will give you the textual descriptions:
$status.Keys | where { $_ -band $value } | foreach { $status.Get_Item($_) }
You could define the enum in Powershell, but the above works just as well, and defining enums in Powershell seems like a lot of work.
Here is an article, that talks about how to use the bitwise operators in Powershell.
You can let PowerShell do more of the work for you. Here's an example using System.IO.FileOptions:
PS> [enum]::GetValues([io.fileoptions]) | ?{$_.value__ -band 0x90000000}
RandomAccess
WriteThrough