dwwilson66
dwwilson66

Reputation: 7066

How do I write Set-Content to a file using Powershell?

I'm doing a number of string replacements in a PowerShell script.

foreach ($file in $foo) {
    $outfile = $outputpath + $file
    $content = Get-Content ($file.Fullname) -replace 'foo','bar'
    Set-Content -path $outfile -Force -Value $content 
}

I've validated (through console logging of $outfile and $content, which I don't show in the above code) that the proper files are being selected, the -replace is accuratly updating the content, and the $outfiles are being created. However, each of the output files a 0 byte file. The Set-Content line does not appear to be writing the data to the files. I've tried piping Set-Content to Out-File, but that just gives me an error.

When I replace Set-Content with Out-File, I get a runtime error Out-File : A parameter cannot be found that matches parameter name 'path'. even though I can output $outfile to the console and see that it's a valid path.

Is there an additional step (like a close-File or save-file command) I need to take or a different order in which I need to pipe something to get the $content to write to my $outfile? What component am I missing?

Upvotes: 4

Views: 15405

Answers (1)

user189198
user189198

Reputation:

The Out-File cmdlet does not have a -Path parameter, however it does have a -FilePath parameter. Here is an example of how to use it:

Out-File -FilePath test.txt -InputObject 'Hello' -Encoding ascii -Append;

You will also need to wrap the Get-Content command in parentheses, as it does not have a parameter called -replace.

(Get-Content -Path $file.Fullname) -replace 'foo','bar';

I'd also recommend adding the -Raw parameter to Get-Content, so that you ensure that you're only dealing with a single line of text, rather than an array of strings (one [String] per line in the text file).

(Get-Content -Path $file.Fullname -Raw) -replace 'foo','bar';

There isn't enough information to completely understand what's going on, but here is a filled out example of what I think you're trying to do:

# Create some dummy content (source files)
mkdir $env:SystemDrive\test;
1..5 | % { Set-Content -Path $env:SystemDrive\test\test0$_.txt -Value 'foo'; };

# Create the output directory
$OutputPath = mkdir $env:SystemDrive\test02;

# Get a list of the source files
$FileList = Get-ChildItem -Path $env:SystemDrive\test -Filter *.txt;

# For each file, get the content, replace the content, and 
# write to new output location
foreach ($File in $FileList) {
    $OutputFile = '{0}\{1}' -f $OutputPath.FullName, $File.Name;
    $Content = (Get-Content -Path $File.FullName -Raw) -replace 'foo', 'bar';
    Set-Content -Path $OutputFile -Value $Content;
}

Upvotes: 5

Related Questions