Reputation: 343
Hey guys i´m just starting with powershell, now I´ve got this problem. I try to check wheater the last character of a inputed path is a "\". But when I run this code the variable $lastRootPathChar is empty. The $end and $start variables get the integers I want them to have, but the .Substring seems to return nothing. What am I doing wrong?
$RootPath = Read-Host 'Please enter the rootpath: '
$start = $RootPath.Length-1
$end = $RootPath.Length
$lastRootPathChar = $RootPath.Substring($start,$end)
if($lastRootPathChar -ne "\")
{
$RootPath = $RootPath + "\"
}
Upvotes: 0
Views: 192
Reputation: 148
$lastRootPathChar = $RootPath.Substring($RootPath.length -1)
This will get the slash out. As $RootPath.length -1 is the index of the last character and there are no characters after that.
Upvotes: 0
Reputation: 136124
The two parameters passed to that overload of String.Substring
are start and length not start and end
$lastRootPathChar = $RootPath.Substring($start,1)
Upvotes: 1
Reputation: 174575
The second argument to "".Substring()
is the total length of the desired substring, not the end index.
$LastChar = $RootPath.Substring($start, 1)
You could also use the index operator []
to access the last char
in the string (index -1
):
$LastChar = $RootPath[-1] -as [string]
Upvotes: 1