This question already has answers here:
$string.Substring Index/Length exception
(3 answers)
Closed 5 years ago.
I'm trying to use Substring() function in PowerShell. This is the example :
$string = "example string"
$temp = $string.Substring(5,($string.Length))
In this example I'm trying to get part of $string, from the 5th char, until the end. I'm using the .Length property to get the last index of $string.
The problem is that I'm getting this exception :
Exception calling "Substring" with "2" argument(s) because of .Length property.
What can I do to get part of $string until the last char?
$string.Length indicates you want a substring that is as long as $string, which is not possible if you are starting at the 5th character of $string. [documentation]
Specify $string.Length - 5 or - much simpler - omit the 2nd argument
$string = "example string"
$temp = $string.Substring(5,($string.Length - 5))
$temp = $string.Substring(5) # much simpler
This Tip of the Week helps to get to grips with PowerShell string manipulation.
Related
This question already has answers here:
Check if string contains numeric value in PowerShell?
(7 answers)
Closed 1 year ago.
How can you check if the whole string is a number?
You can check if a string contains a number with regular expression. Can you use regular expressions as well to find out if a string is only a number, without any other characters?
"abc" is supposed to be false, it's not a number
"abc12" is supposed to be false, it's not a number
"123" is supposed to be true
if you are not using variables, and literal which is one quote, exactly what is in between the quotes.
'abc' -is [String]
'abc12' -is [String]
'123' -is [String]
This question already has answers here:
Scala: Splitting with Double Quotes ("") vs Single Quotes ('')
(4 answers)
Closed 2 years ago.
I am working on spark - scala and find out that in scala. the splitting is different than python. As an example:
My function:
for (line <- lines) {
var fields = line.split("|")
if(fields.length > 1){
movieNames += (fields(0).toInt -> fields(1))
}
gives me an ERROR but when I change it to ...
for (line <- lines) {
var fields = line.split('|')
if(fields.length > 1){
movieNames += (fields(0).toInt -> fields(1))
}
then, It will solve so, what is the difference between " | " and ' | ' at logic level.
The docs are your friend.
line.split("|") calls the split version that receives a String, such version treats that String as a regex.
And | is not a valid regex.
Whereas line.split('|') calls the split version that receives a Char, such version just split the line every time it finds that character.
$fileName = "Name of TheFolder_NE_ED"
$lengthFileName = $fileName.length
$shortenLengthFileName = $lengthFileName - 5
Write-Host("Name of TheFolder_NE_ED").Substring($shortenLengthFileName,$lengthFileName)
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
I am having a problem with SubString() function, it errors with:
I tried printing out values of my variables but they seemed fine.
In PowerShell, substring works in a slightly different way.
With your existing code you could try this:
$fileName = "Name of TheFolder_NE_ED"
$lengthFileName = $fileName.length
$shortenLengthFileName = $lengthFileName - 5
Write-Host("Name of TheFolder_NE_ED").Substring($shortenLengthFileName)
Explanation:
The first parameter inside Substring should be the starting index of the character(in this case 18). Now from that letter it will start counting till the character (which you have to pass as a second parameter). Else it will by default go to the end of the string.
So, if you want to pass 2 parameters and do that, then change it to:
Write-Host("Name of TheFolder_NE_ED").Substring($shortenLengthFileName,5)
For further reference, follow Substring Use
Hope it helps.
I'm returning some data like this in powershell :
1)Open;#1
2)Open;#1;#Close;#2;#pending;#6
3)Closed;#5
But I want an output like this :
1)1 Open
2)
1 Open
2 Close
6 pending
3)
5 Closed
The code:
$lookupitem = $lookupList.Items
$CMRSItems = $list.Items | where {$_['ID'] -le 5}
$CMRSItems | ForEach-Object {
$realval = $_['EventType']
Write-Host "RefNumber: " $_['RefID']
Write-Host $realval
}
Any help would be appreciated as my powershell isn't that good.
Without regular expressions, you could do something like the following:
Ignore everything up to the first ')' character
Split the string on the ';' character
foreach pair of the split string
the state is the first part (ignore potentially leading '#')
the number is the second part (ignore leading '#')
Or you could do it using the .NET System.Text.RegularExpressions.Regex class with the following regular expression:
(?:#?(?<state>[a-zA-Z]+);#(?<number>\d);?)
The Captures property on the MatchCollection returned by the Matches method would be a collection in which each item will contain two instances in the Group collection; named state and number respectively.
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