Pranav
Pranav

Reputation: 695

Direct un-buffered writes in Powershell

Currently I am trying to run a test that will power-down the machine abruptly when a file is being written. When power-down occurs the last part of data is not present as it is never flushed to disk before power down.

Perl (in Linux) allows direct un-buffered writes when a file is opened in the following manner.

sysopen(F, $file, O_WRONLY|O_DIRECT) or die "Couldn't direct open file $file\n";

This allows data to be written till the last character in-case machine crashes due to some reason. Likewise, for windows, C++ allows direct writes when a file is opened for writes using "FILE_FLAG_NO_BUFFERING" flag.

How can I allow direct/un-buffered writes to disk using powershell ?

Upvotes: 0

Views: 814

Answers (1)

Keith Hill
Keith Hill

Reputation: 201632

You could drop down to .NET and use a FileStream object to write the file. Use the constructor that takes FileOptions and try the FileOptions.WriteThrough enum value, e.g.:

$fileStream = New-Object System.IO.FileStream($file,
    [System.IO.FileMode]::Create, 
    [System.Security.AccessControl.FileSystemRights]::Modify,
    [System.IO.FileShare]::None,
    1,
    [System.IO.FileOptions]::WriteThrough)

Upvotes: 1

Related Questions