8

フォルダー内のすべてのファイルで「%%」で始まる各行を抽出し、それらの行を別のテキスト ファイルにコピーしようとしています。現在、このコードを PowerShell コードで使用していますが、結果が得られません。

$files = Get-ChildItem "folder" -Filter *.txt
foreach ($file in $files)
{
if ($_ -like "*%%*")
{
Set-Content "Output.txt" 
}  
}
4

4 に答える 4

17

使用する mklement0 の提案が道だと思いますSelect-String。彼の答えに加えて、プロセス全体が Powershell ワンライナーになるように、の出力Get-ChildItemをパイプすることができます。Select-String

このようなもの:

Get-ChildItem "folder" -Filter *.txt | Select-String -Pattern '^%%' | Select -ExpandProperty line | Set-Content "Output.txt"
于 2016-12-09T07:52:10.727 に答える
1

まず、使用する必要があります

取得コンテンツ

ファイルの内容を取得するため。次に、文字列の一致を行い、それに基づいてコンテンツをファイルに戻します。get-contentを使用し、 foreach内に別のループを配置して、ファイル内のすべての行を反復処理します。

このロジックがお役に立てば幸いです

于 2016-12-09T04:09:55.597 に答える
1
ls *.txt | %{
$f = $_
  gc $f.fullname | {
     if($_.StartWith("%%") -eq 1){
        $_ >> Output.txt
     }#end if
  }#end gc
}#end ls

エイリアス

ls - Get-ChildItem
gc - Get-Content
% - ForEach
$_ - Iterator variable for loop
>> - Redirection construct
# - Comment

http://ss64.com/ps/

于 2016-12-09T04:07:20.170 に答える