Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PowerShell remove LineFeed & CarageReturn from Get-CimInstance

I’m working on a new script and to make things easier for me in the long run I need to put everything manually in a form to keep track. Now I love that the list is mostly clean, but I would like the following.

I run:

$PrL = (Get-CimInstance -Class CIM_Printer).Name | Sort-Object

Result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Printer01
Printer02
Printer03
Printer04

Output I try to achieve:

Printer01; Printer02; Printer03; Printer04

I manage to either put ; at the end of each line or to have each entry be written one after the other.

Of course I could use Notepad++ and replace "\r\n" with "; " but that takes more time. I would like to be able to automate this but so far I only get one after the other.

Here are some attempts.

Attempt 1:

$PrL = (Get-CimInstance -Class CIM_Printer).Name | Sort-Object
$PrL2 = ForEach-Object { $PrL -replace '\r', ' '}

Attempt 2:

$PrL = (Get-CimInstance -Class CIM_Printer).Name | Sort-Object
$PrL2 = $PrL | ForEach { $_ +  "; " }
$PrL2 | ForEach { $_ -replace '\r', ' '}

Attempt 3:

$PrL = (Get-CimInstance -Class CIM_Printer).Name | Sort-Object
$PrL | ForEach-Object { $_ -replace '\n', " "}

I don’t even know if \r or +r or `r or something else entirely is required and I basically tried copy paste some things that people have tried but those only work in parts or not at all.

Current PowerShell Version: 5.1.19041.3930
OS: Windows 10 Pro

>Solution :

Use the pattern \r?\n instead – by marking the \r optional with ? it’ll match both CRLF and LF-style line endings:

(Get-CimInstance -Class CIM_Printer).Name -replace '\r?\n',' '

Based on your listed output it doesn’t look like any of the printer names have any line breaks in their names.

If you want to take an existing array of string values and join them into a single string, use the -join operator:

$semiColonSeparatedListOfPrinterNames = (Get-CimInstance -Class CIM_Printer).Name -join '; '

$semiColonSeparatedListOfPrinterNames will now print on a single line

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading