Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell [System.IO.File]::WriteAllLines not working [duplicate]

What's wrong with these PowerShell Commands. its doesn't write the file "test.txt"

PS> $stuff = @("AAA`n", "BBB`n")
PS> [System.IO.File]::WriteAllLines(".\test.txt", $stuff)
PS> dir
# Nothing here....

Is there anything misconfigured on my Computer that could cause this? Do I need to somehow reinstall .net?

like image 455
pico Avatar asked Mar 05 '26 16:03

pico


2 Answers

Try dir ~\test.txt - or use an absolute path c:\path\to\my\test.txt. Better yet look at the Set-Content cmdlet.

FYI: theres nothing wrong with your computer - your using a dotnet library so you need to be more specific (basically). Set-Content is the powershell way of doing this (and .\test.txt would work as your were expecting).

like image 124
MisterSmith Avatar answered Mar 08 '26 08:03

MisterSmith


.Net doesn't use the same path as your PowerShell. The solution is to resolve a relative path into a fullpath:

PS C:\> $stuff = @("AA", "BB")
PS C:\> $out_file = ".\out.txt"
PS C:\> New-Item -Force -Path $out_file
PS C:\> $out_full = $(Resolve-Path -Path $out_file)
PS C:\>[System.IO.File]::WriteAllLines(` 
    ".\testing.txt", $out_full)

A better way:

function open_w {
    param([string]$path)
    write-host "path: $path"
    $pathfix =  $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($path)
    return [System.IO.StreamWriter]::new($pathfix)
}
like image 40
pico Avatar answered Mar 08 '26 06:03

pico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!