遲到了,但認爲這可能是有用的。我需要對超過一千個以上的大文件執行操作,並且需要一些更強大的功能,並且不太容易出現OOM異常。最終只是寫它利用.NET庫:
function PrependTo-File{
[cmdletbinding()]
param(
[Parameter(
Position=1,
ValueFromPipeline=$true,
Mandatory=$true,
ValueFromPipelineByPropertyName=$true
)]
[System.IO.FileInfo]
$file,
[string]
[Parameter(
Position=0,
ValueFromPipeline=$false,
Mandatory=$true
)]
$content
)
process{
if(!$file.exists){
write-error "$file does not exist";
return;
}
$filepath = $file.fullname;
$tmptoken = (get-location).path + "\_tmpfile" + $file.name;
write-verbose "$tmptoken created to as buffer";
$tfs = [System.io.file]::create($tmptoken);
$fs = [System.IO.File]::Open($file.fullname,[System.IO.FileMode]::Open,[System.IO.FileAccess]::ReadWrite);
try{
$msg = $content.tochararray();
$tfs.write($msg,0,$msg.length);
$fs.position = 0;
$fs.copyTo($tfs);
}
catch{
write-verbose $_.Exception.Message;
}
finally{
$tfs.close();
# close calls dispose and gc.supressfinalize internally
$fs.close();
if($error.count -eq 0){
write-verbose ("updating $filepath");
[System.io.File]::Delete($filepath);
[System.io.file]::Move($tmptoken,$filepath);
}
else{
$error.clear();
write-verbose ("an error occured, rolling back. $filepath not effected");
[System.io.file]::Delete($tmptoken);
}
}
}
}
用法:
PS> get-item fileName.ext | PrependTo-File "contentToAdd`r`n"
這很棒!謝謝! – thomaskessel
'Set-Content'將在文件末尾添加額外的換行符。 – PetSerAl
@PetSerAl並不是我通常會注意的事情,但是增加了一個小記錄。 – Matt