2016-12-07 34 views
0

我想從輸入文件中獲得所有行,從%%開始,並使用powershell將其粘貼到輸出文件中。從文本文件複製特定的行,以使用powershell分離文件

用下面的代碼,但是我只得到首發輸出文件的最後一行與%%所有的線,而不是開始%%

我只有開始學習PowerShell中,請大家幫忙

$Clause = Get-Content "Input File location" 
$Outvalue = $Clause | Foreach { 
    if ($_ -ilike "*%%*") 
    { 
     Set-Content "Output file location" $_ 
    } 
} 

回答

0

您遍歷文件中的行,並設置每一個作爲文件的全部內容,每次覆蓋以前的文件。

你需要或者改用Add-Content代替Set-Content,這將追加到該文件,或改變設計:

Get-Content "input.txt" | Foreach-Object { 
    if ($_ -like "%%*") 
    { 
     $_  # just putting this on its own, sends it on out of the pipeline 
    } 
} | Set-Content Output.txt 

,你會更通常寫爲:

Get-Content "input.txt" | Where-Object { $_ -like "%%*" } | Set-Content Output.txt 

並且在外殼中,您可能會寫爲

gc input.txt |? {$_ -like "%%*"} | sc output.txt 

對整個文件進行過濾,然後將所有匹配行一次發送到Set-Content,而不是分別爲每行調用Set-Content。

注意: PowerShell默認情況下不區分大小寫,因此-like-ilike表現相同。

相關問題