关于去掉末尾指定内容


PowerShell交流中心关于去掉末尾指定内容
0
flyfree asked 5 年 ago

我百度过这个方法

举个例子,有一个字符串$s=”domain.com.”,想要去掉最后尾巴上的点,
$s.SubString(0,$s.Length-1)
这个方法的作用更确切来讲,是把最后一个字符去掉,这个的确是我想要的。

我的目的就是$UninstallFldr这个变量内容里的”\”去掉

但是发现到我自己具体的脚本上很奇怪,我在直接运行脚本的时候因为这个变量是从注册表里面获取的,运行命令的时候会报错,如果我在命令行自己定义这个$UninstallFldr变量的话就可以正常运行

这个脚本 $UninstallFldr = $UninstallFldr.Substring(0,(“$UninstallFldr”.Length-1))。

#下面这行变量是我从脚本里获取的变量内容,运行结果是失败的。

PS C:\WINDOWS\system32> $UninstallFldr
C:\Mentorhello\world\

PS C:\WINDOWS\system32> $UninstallFldr = $UninstallFldr.Substring(0,(“$UninstallFldr”.Length-1))
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:1
+ $UninstallFldr = $UninstallFldr.Substring(0,(“$UninstallFldr”.Length- …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException

#下面这个我自己直接定义这个变量后运行就是没有问题的

PS C:\WINDOWS\system32> $UninstallFldr = “C:\Mentorhello\world\”

PS C:\WINDOWS\system32> $UninstallFldr = $UninstallFldr.Substring(0,(“$UninstallFldr”.Length-1))

PS C:\WINDOWS\system32> $UninstallFldr
C:\Mentorhello\world

 

1 Answers
2
Best Answer
Mooser Lee 管理员 answered 5 年 ago

长度越界了,比如这样
PS> ‘ss’.Substring(1,2323) Exception calling “Substring” with “2” argument(s): “Index and length must refer to a location within the string. Parameter name: length”
去掉最后一个字符,直接可以这样
$str.TrimEnd(‘\’)
 

flyfree replied 5 年 ago

再次感谢