Friday, November 13, 2015

New no new line in PowerShell 5

To write information to a log file, we can use Out-File, Set-Content, or Add-Content. (There are, of course, other ways, but this article is about a new feature in those three.) Up to now, it has always been challenging or at least ugly when you wanted to slowly build a lot information into a single line, because you could only write an entire line at a time.

You may have had to store a line in a variable until it was complete and then write it to the file. Or you might have had to do something like this.

"$(Get-Date) - Computers accessed: $($Computers.Name -join ", ")" | Out-File $LogFile -Append

In PowerShell 5, a new parameter was added to Out-File, Set-Content and Add-Content, -NoNewLine.

So now, we can do something like this:

Get-Date                   | Out-File $LogFile -Append -NoNewline
" - Computers accessed: "  | Out-File $LogFile -Append -NoNewline
$Computers.Name -join ", " | Out-File $LogFile -Append

(Yes, it's a stupid example. But you see what I'm getting at.)

And of course it works with the other ones as well.

$X | Out-File    $LogFIle -NoNewline
$X | Set-Content $LogFile -NoNewLine
$X | Add-Content $LogFile -NoNewLine

No comments:

Post a Comment