Add-Content或substring将回车添加到变量

时间:2012-09-21 18:34:36

标签: powershell substring carriage-return

我输出了一些我从文件中提取的文本行,当我在$ strAcct之后输出此部分时,正在添加回车符:

Add-Content "C:\TestFile-Output.txt" ($strAcct+$strPart2)

基本上,文件中的打印是$ strAcct 回车/换行 $ strPart2

这是我的所有代码:

#Setting Variables
$data = get-content "C:\TestFile.txt"
$strAcct= @()
$strPart1= @()
$strPart2= @()
$strLength= @()


#For each line of text in variable $data, do the following
foreach($line in $data)
{
  #reseting variables for each time the FOR loop repeats
  $strAcct= @()
  $strPart1= @()
  $strPart2= @()
  $strLength= @()


   #We're saying that if the line of text is over 180 characters, were going to split it up into two different lines so MEDITECH can accept this note files
   if ( $line.length -gt 180)
   { $strLength = $line.length
     $strAcct += $line.substring(0,22) 
     $strPart1 += $line.substring(0,180)
     $strPart2 += $line.substring(181)

     #Create first and second line in text file for the string of text that was over 180 characters
     Add-Content "C:\TestFile-Output.txt" $strPart1
     Add-Content "C:\TestFile-Output.txt" ($strAcct+$strPart2)



   } 
   #If our line of text wasn't over 180 characters, just print it as is
   Else {
   Add-Content "C:\TestFile-Output.txt" $line

   }

}

1 个答案:

答案 0 :(得分:3)

您的代码中

$strAcct $strPart1 $strPart2都是数组,我认为这不是您的意图。默认情况下,将每个字符串发送到一个新行中(即由CR-NL分隔)。

如果您尝试根据代码中的启发式将长行拆分为2行,则下面应该有效:

$data = get-content "C:\TestFile.txt"    

#For each line of text in variable $data, do the following
foreach($line in $data)
{   
   $newContent = 
     if ($line.length -gt 180)
     {
       $part1 = $line.substring(0,180)         
       $part2 = $line.substring(181)
       $acct = $line.substring(0,22)

       $part1
       $acct + $part2
     } 
     else
     {
       $line
     }

   Add-Content "C:\TestFile-Output.txt" $newContent
}