2012-09-21 37 views
0

我收到以下代碼的錯誤。我試圖在超過180個字符的文本文件中將行分析並將它們解析爲新行。我不得不採取的第一個22個字符,並把它從第二部分,因爲它其中包含的需要就行inital數據:子字符碼錯誤 - Powershell

$data = get-content "C:\TestFile.txt" 
$strAcct= @() 
$strPart1= @() 
$strPart2= @() 
$strLength= @() 
foreach($line in $data) 
{ 
    if ($line.length -gt 181) 
    { $strLength = $line.length 
    $strAcct += $line.substring(0,22) 
    $strPart1 += $line.substring(0,180) 
    $strPart2 += $line.substring(181,$strLength) 

    Add-Content "C:\TestFile-Output.txt" $strPart1 
    Add-Content "C:\TestFile-Output.txt" $strAcct $strPart2 



    } 
    Else { 
    Add-Content "C:\TestFile-Output.txt" $line 

    } 

} 

回答

1

子串接受一個索引,字符數採取從指數開始。你的第三個子串炸彈,因爲你想要比字符串中更多的字符。將其更改爲$ strLength - 181,或者,也可以將第二個參數完全取出,以從第一個參數中的索引開始取其餘的字符串。

更改此:

$line.substring(181, $strLength) 

這樣:

$line.substring(181) 

,甚至這樣的:

$line.substring(181, $strLength - 181) 
+0

我想工作,謝謝。我收到一個炸彈:添加內容「C:\ TestFile-Output.txt」$ strAcct $ strPart2 如何打印$ strAcct AND $ strPart2 – Noesis

+0

添加內容「C:\\ TestFile-Output。 txt「($ strAcct + $ strPart2) –

+0

它將strPart2放在新行上,而不是與$ strAcct同一行。有任何想法嗎? – Noesis