2

I'm extracting fields from Active Directory and piping that into a .csv file, My Select-Object command returns the fields by name. My problem is some of these fields contain carriage return and line feed information I want to remove before piping it into the .csv

Example:

Select-Object SamAccountName,displayName,info | ConvertTo-CSV -NoTypeInformation | 
Out-File -Append -FilePath $Filepath -Encoding unicode

How can I intercept and amend the 'info' field before firing it to .csv?

Thanks.

2 Answers 2

4

You could remove carriage return and line feed using regex. Try next snippet:

Select-Object -property SamAccountName, DisplayName, Info |
    % {
        $_.SamAccountName = [regex]::Replace($_.SamAccountName, "(`n|`r)+"," ", "Multiline");
        $_.DisplayName= [regex]::Replace($_.DisplayName, "(`n|`r)+"," ", "Multiline");
        $_.Info = [regex]::Replace($_.Info, "(`n|`r)+"," ", "Multiline");
        return $_;
    } | 
    ConvertTo-CSV -NoTypeInformation | 
    Out-File -Append -FilePath $Filepath -Encoding unicode
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Akim, thanks for the response.Not sure what's going on there but I now get ÿþ as an output, just once - that's the new content of the entire document rather than the 3k lines expected.
sorry, i'd forget to add return $_;. Try snippet now
I still receive the same output. No worries though I've resorted to adding a line to manipulate the finished file to remove the information I needed to. Thanks very much for your assistance.
1

You can intercept the output using a calculated property:

Select-Object SamAccountName,displayName,{$_.info.replace("`r", "").replace("`n", "")} 
    | ConvertTo-CSV -NoTypeInformation 
    | Out-File -Append -FilePath $Filepath -Encoding unicode

The backtick ` allows you to insert special characters `r is carriage return and `n is new line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.