Home > Software engineering >  powershell [System.IO.File]::WriteAllLines not working
powershell [System.IO.File]::WriteAllLines not working

Time:10-23

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?

CodePudding user response:

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).

CodePudding user response:

.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)
  • Related