Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Out-File -force, Intermediate directories are not created

Tags:

powershell

My code is:

$path = "c:\no-such-dir\00.txt"
"foo" | Out-File -force -filePath $path

The error:

Out-File : Could not find a part of the path 'C:\no-such-dir\00.txt'

help out-file -full

For example, Force will override the read-only attribute or create directories to complete a file path, but it will not attempt to change file permissions.

So it seems it should create 'no-such-dir', but it does not. What happens?

like image 555
alex2k8 Avatar asked Apr 02 '09 23:04

alex2k8


2 Answers

This looks like a bug. Per http://www.vistax64.com/powershell/62805-out-file-force-doesnt-seem-work-advertised.html, this issue has already been filed on MS Connect.

like image 167
Michael Avatar answered Nov 24 '22 18:11

Michael


As mentioned by Micheal, this looks like a bug (or false advertising!).

EDIT: I initially thought that the ">" operator worked, but I made a mistake in my test. It does not, as one would expect. However, you can try using new-item instead:

new-item -force -path $path -value "bar" -type file

Not exactly the same, but you can create a simple function to do what you want:

function Out-FileForce {
PARAM($path)
PROCESS
{
    if(Test-Path $path)
    {
        Out-File -inputObject $_ -append -filepath $path
    }
    else
    {
        new-item -force -path $path -value $_ -type file
    }
}
}
like image 33
zdan Avatar answered Nov 24 '22 17:11

zdan