user3474661
user3474661

Reputation: 59

Delete carriage return in powershell

I having troubles deleting carriage return within a text file. I want to delete carriage return just for "Message". I need the "Message" content to be on just one line.

My input looks like:

TimeCreated      : 08/04/2014 22:31:15
LevelDisplayName : Information
Id               : 50065
Message          : DHCP a trouvé dans le cache une corespondance pour l’identificateur                  
                  (Service Set Identifier) Livebox-816F (valeur hexadécimale de 
                   l’identificateur SSID : C496674) pour la carte réseau dont l’adresse 
                   réseau est 0x0C

I came up with this line of code but it doesn't work:

$MyObject = Get-WinEvent -LogName 'Microsoft-Windows-Dhcp-Client/Admin' | Where-Object {$_.TimeCreated -ge $lastsevendays} | Select 'TimeCreated', 'LevelDisplayName', 'ID', @{n='Message';e={$_.Message -replace '`r', " "}}, $Size 
$MyObject > $SourceFile

Thanks a lot!

Upvotes: 4

Views: 17856

Answers (4)

Mark Minasi
Mark Minasi

Reputation: 413

Probably a stupid journeyman answer, but I had a similar problem and something like this worked:

$newdelimiter=" "
$f=get-command attach.txt -raw
$f -replace "\r\n",$newdelimiter

May have missed the point, apologies if I did. Works for me to take huge hunks of HTML and do screen scraping on it.

Upvotes: 0

skataben
skataben

Reputation: 2152

Update:

It's not clear whether or not the OP wants to remove CRs only or CRLFs. For "Message content to be on just one line", you need to remove both CRs and LFs.

@latkin makes a good point noting that the OP might be concerned about not only the property values but the formatted PowerShell output.

To remove both CRs and LFs from the actual property values:

$MyObject = Get-WinEvent -LogName 'Microsoft-Windows-Dhcp-Client/Admin' | where TimeCreated -GE $lastsevendays | Select TimeCreated, LevelDisplayName, Id, Message | Remove-NewLines | fl

$MyObject > $sourceFile

Update 2:

fl (Format-List), however, will wrap the output based on your console width. To prevent that, pipe to Out-String using the max width (then remove only the CRs if that is your intention):

$MyObject = Get-WinEvent -LogName 'Microsoft-Windows-Dhcp-Client/Admin' | where TimeCreated -GE $lastsevendays | Select TimeCreated, LevelDisplayName, Id, Message | Remove-NewLines | fl | Out-String -Width 2147483647 | Remove-NewLines -CR

$MyObject > $sourceFile

Using this general-purpose filter:

filter Remove-NewLines([string[]]$Name = '*', [switch]$CR, [switch]$LF)
{
    $crlf = @{ CR = "`r"; LF = "`n" }
    $newLine = $crlf.Keys | where { $PSBoundParameters.ContainsKey($_) } | foreach { $crlf[$_] }

    if (-not $newLine)
    {
        $newLine = "`r", "`n"
    }

    $newLine = $newLine -join '|'

    if ($_ -is [string] -or $_ -is [ValueType])
    {
        return $_ -replace $newLine
    }

    $object = $_ | select *

    $object.psobject.Properties | 
        where IsSettable |
        where {
            $propertyName = $_.Name
            $Name | where { $propertyName -like $_ } | select -First 1
        } |
        foreach { try { $_.Value = $_.Value -replace $newLine } catch { } }

    $object
}

Example 1:

PS> Get-WinEvent -LogName 'Microsoft-Windows-Dhcp-Client/Admin' | Remove-NewLines

Removes CRs and LFs from all properties.

Example 2:

PS> Get-WinEvent -LogName 'Microsoft-Windows-Dhcp-Client/Admin' | Remove-NewLines M* -CR

Removes CRs from the Message property.

Upvotes: 0

TheMadTechnician
TheMadTechnician

Reputation: 36342

Arg, SO timed out on me and killed my answer. Here, this worked for me. I saved your sample text to a file C:\Temp\Test.txt. Then I ran this script against it:

$Logs = GC C:\Temp\test.txt
$Event = New-Object PSObject
for($i=0;$i -lt $logs.count;$i++){
    If($Logs[$i] -match "^\S"){
        $Current = $logs[$i].split(":")
        Add-Member -InputObject $Event -MemberType NoteProperty -Name $Current[0].TrimEnd(" ") -Value $Current[1].TrimStart(" ")
        $last = $current[0].TrimEnd(" ")}
    else
    {$Event.$last = $event.$last+$logs[$i].TrimStart(" ")}
}

That leaves me with $Event which is an object that has 4 properties:

  • TimeCreated
  • LevelDisplayName
  • Id
  • Message

Where $Event.Message is a single string as you desired in your request.

Edit: Seeing that you are outputting events, it looks like you're having wrapping issues due to width constraints. Instead of $MyObject > $SourceFile do this:

$MyObject|fl|Out-File test1.txt -Width $($($MyEvent.Message.Length)+20)

That will output it like what you had except it will have each item on it's own line, and it will format the width to be the length of the Message property + 20 characters to allow for the Message : before it.

Upvotes: 0

mjolinor
mjolinor

Reputation: 68341

Try this (folded at the pipes for readability):

$MyObject = Get-WinEvent -LogName 'Microsoft-Windows-Dhcp-Client/Admin' |
 Where-Object {$_.TimeCreated -ge $lastsevendays} |
  Select 'TimeCreated', 'LevelDisplayName', 'ID', @{n='Message';e={$_.Message -replace '\r', " "}} 

$MyObject > $SourceFile

The escape character in the Powershell parser is the backtick, but those rules don't apply within the regex argument for -Replace. There you have to use regex parsing rules, and a carriage return is '\r'

Note: if you want it all as a single line, you'll also have to replace the newline, so your replace would be '\r\n',''

Upvotes: 1

Related Questions