[英]PowerShell Substring “Index Outside of String Length”
I have a List of Filenames which I have to split in a certain way.我有一个必须以某种方式拆分的文件名列表。 The easiest way I know is to use Substring on them.
我知道的最简单的方法是在它们上使用 Substring。
The Filenames are formatted like;文件名的格式如下; VLAN_[Random Name]_[Random Number].ini
VLAN_[随机名称]_[随机数].ini
So my guess was to use Substring to get the Filename from the 5th to the 4th last Postion所以我的猜测是使用 Substring 来获取文件名从第 5 到第 4 最后 Postion
$FileList = Get-ChildItem -Path $FileDir | Where-Object -Property name -like "VLAN_*"
ForEach($File in $FileList){
[String]$SheetName = $File.Name # Name Formatted like: VLAN_[Random Name]_[Random Number].ini
$SheetName = $SheetName.Substring(5,$Sheetname.Length-4)
Write-Host $File.Name
Write-Host $SheetName
Read-Host
}
When I tried with this it gave me back an "Index is not in String length" Error, but when I used a 4 or less as a Starting point for my Substring it worked.当我尝试这样做时,它给了我一个“索引不是字符串长度”错误,但是当我使用 4 或更少作为我的 Substring 的起点时,它起作用了。 Does it have something to do with the "_" symbol?
它与“_”符号有关吗? Also, when I start from 0 the last 4 chars get deleted like they should, but if the starting point isn't 0 it never deletes the last 4 chars.
此外,当我从 0 开始时,最后 4 个字符会被删除,但如果起点不是 0,它永远不会删除最后 4 个字符。
Heres the Output I get with both Substring methods:这是我使用两种 Substring 方法得到的 Output:
# Substring(5,$Sheetname.Length-4)
"Index is not in String length" Error
VLAN_BMA_201.ini
VLAN_BMA_201.ini
"Index is not in String length" Error
VLAN_CCTV_120.ini
VLAN_CCTV_120.ini
# Substring(4,$Sheetname.Length-4)
VLAN_BMA_201.ini
_BMA_201.ini
VLAN_CCTV_120.ini
_CCTV_120.ini
If your file names always have the same structure with the underlines in it you can make this task a lot easier with the split method like this:如果您的文件名始终具有与其中的下划线相同的结构,您可以使用以下拆分方法使此任务更容易:
ForEach($File in $FileList){
($File.BaseName -split '_' )[1..2] -join '_'
}
The second parameter in Substring()
is the length of the substring, so when you say that is <LengthOfString>-4
and you are starting the substring at position 5, you will always be going beyond the length of the string. Substring()
中的第二个参数是 substring 的长度,所以当你说它是<LengthOfString>-4
并且你从 position 开始 substring 时,你总是会超出字符串 5 的长度。 You need to add the first 5 characters you are skipping to what you subtract to the length of the substring.您需要将要跳过的前 5 个字符添加到您减去 substring 的长度。 So try
$SheetName = $SheetName.Substring(5,$Sheetname.Length-9)
instead and you should get what you want.所以尝试
$SheetName = $SheetName.Substring(5,$Sheetname.Length-9)
,你应该得到你想要的。
Alternatively, use a simple regular expression:或者,使用简单的正则表达式:
if ($SheetName -match 'VLAN_(?<stuffIcareAbout>.+)\.ini')
{
$SheetName = $Matches.stuffICareAbout
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.