tags:

views:

128

answers:

2

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?

+4  A: 

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.

Michael
+3  A: 

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
    }
}
}
zdan
Are you sure it works for you? I am using PowerShell v2, and it does not work.
alex2k8
I did try it. but I made the mistake of forgetting to delete the intermediate directory, sorry.
zdan
New-Item works perfect, thank you!
alex2k8