Home > Enterprise >  Read files, modify content and write new files
Read files, modify content and write new files

Time:10-29

I am trying to modify the contents of a set of files in one folder and write the modified files to another folder. The modification bit is easy and works well, but setting new content is failing. Here is the code:

$files = Get-ChildItem "~\Desktop\Test1\*.txt"
foreach ($f in $files)
{
Get-Content "$f" |
Where-Object { -not $_.Contains('VOID') } |
Set-Content "~\Desktop\Test2\$f"
}

The error I get when running is: Set-Content : Could not open the alternate data stream '\Users\Laptop\Desktop\Test1\test.txt' of the file '\Users\Laptop\Desktop\Test2\C'.

What does it mean "Test2\C" ?? Where does C come into it?

This must be a very easy fix but I could use some help please.

CodePudding user response:

To ensure that you only use the file name of each input file, replace

"~\Desktop\Test2\$f"

with

"~\Desktop\Test2\$($f.Name)"

If you stringify $f as a whole ("$f"), the .ToString() method is called on the System.IO.FileInfo instance it represents, which returns the full path (typically in Windows PowerShell, always in PowerShell (Core) 7 ), so you'll end up with a malformed path such as C:\User\jdoe\Desktop\Test2\C:\User\jdoe\Desktop\Test1\foo.txt - that is, you're effectively appending a full path to another full path.


As for what you tried:

What does it mean "Test2\C" ?? Where does C come into it?

C is the drive letter of the full path that $f stringified to (e.g., C:\User\jdoe\Desktop\Test1\foo.txt)

The reason that the rest of the path is missing is that everything after the (accidental) second : (the first one coming from the drive letter in the expanded form of ~\Desktop\Test1\*.txt) is interpreted as the identifier of an alternate NTFS data stream (ADS).
The error was caused by the fact that is (accidental) identifier contained invalid characters, namely \.

  • Related