2

I am attempting to convert the format of a file to UTF-8 with PowerShell using a technique outlined in another SO question.

I am using the following statement:

[IO.File]::WriteAllLines((Get-Item -Path ".\" -Verbose).FullName,"Test.txt")

The first parameter is the file path (C:\users\rsax\documents\Test), and the second parameter is the name of the file.

However, the command is not working, and is returning the following error:

Exception calling "WriteAllLines" with "2" argument(s): "Access to the path 'C:\users\rsax\documents\Test' is denied."
At line:1 char:25
+ [IO.File]::WriteAllLines <<<< ((Get-Item -Path ".\" -Verbose).FullName,"Test.txt")
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
  • I am running the command from PowerShell as an administrator.
  • I have verified that the file is in the folder.
  • I can run other cmdlets in the directory that access the file, such as:

    Get-Content Test.txt | Out-File TestOut.txt

  • I was not able to find an answer on the MSDN MethodInvocationException page.

What am I doing wrong?

Community
  • 1
  • 1
RSax
  • 305
  • 2
  • 11

2 Answers2

4

I'm not sure you understand the overload you're using. The first argument is supposed to be the filepath, while the second is the content (not the filename). (Get-Item -Path ".\" -Verbose).FullName will be the path of the folder, not the file. Also, the -Verbose switch is not needed.

PS> [IO.File]::WriteAllLines.OverloadDefinitions
static void WriteAllLines(string path, string[] contents)

Sample:

$content = Get-Content .\Test.txt
$outfile = Join-Path (Get-Item -Path ".\Test.txt").DirectoryName "TestOut.txt"
[IO.File]::WriteAllLines($outfile, $content)
Frode F.
  • 46,607
  • 8
  • 80
  • 103
  • 1
    You are right - I didn't understand the overload. Thank you for the solution -- it worked perfectly. – RSax Feb 20 '16 at 00:05
2

WriteAllLines takes the full path of the file, and then the lines of text to write. Don't separate the file parts. Also notice that you are not telling it what to write at all.

$content = 'a','b','c'
$path = (Get-Item -Path ".\" -Verbose).FullName | Join-Path -ChildPath 'Test.txt'
[IO.File]::WriteAllLines($path,$content)
briantist
  • 39,669
  • 6
  • 64
  • 102