aston_zh
aston_zh

Reputation: 6843

Powershell: Write to File -NoNewLine

I have a bunch of foldernames that I want to write to a file. Using replace. My script looks like this:

$file = "C:\Temp\out.txt"
$dirs = gci "C:\Temp\dirs"

foreach ($dir in $dirs){
$d = $dir.Name
(gc $file) -replace "Begin", "Begin`r`n$d" | sc $file
}

I want to write the Folders in one Line, separated by commas, after keyword Begin. How can I format this?

Upvotes: 1

Views: 723

Answers (1)

AdamL
AdamL

Reputation: 13161

Try this:

$file = "C:\Temp\out.txt"
$dirs = gci "C:\Temp\dirs" | Where-Object{$_.PSIsContainer -eq $true}

New-Item $file -ItemType "file" -Force
"Begin" | Out-File $file 

$dirs -join "," | Out-File $file -Append

You'd probably have to add extension filter in where-object, because PSIsContainer may evaluate to true for archive files.

Upvotes: 1

Related Questions