Sandy
Sandy

Reputation: 91

String coming with an extra new line

Below is the code where I am taking server names from a text file and concatenating with comma. But when I am printing the value, it is coming with an extra new line after the values.

I tried doing $erversToReboot.Trim(), but didn't helped.

$ServerList = Get-Content "D:\ServerName.txt"
$Servers=""
foreach($Server in $ServerList)
{

        $Servers += $Server + ","

}

[string]$ServersToReboot= $Servers.TrimEnd(",")

The output coming as

server1,server2
---one extra line here---

Please let me know what is going wrong here.

Upvotes: 0

Views: 170

Answers (2)

mklement0
mklement0

Reputation: 437109

As others have noted, it's in general much simpler to use the -join operator to join the input lines with a specifiable separator.

As for the problem of an extra empty line: Gert Jan Kraaijeveld plausibly suggests that your input file has an extra empty line at the end, while noting that it is actually not what would happen with the code you've posted, which should work fine (despite its inefficiency).

Perhaps the extra line is an artifact of how you're printing the resulting value.


To answer the related question of how to ignore empty lines in the input file:

Assuming that it is OK to simply remove all empty lines from the input, the simplest PowerShell-idiomatic solution is:

@(Get-Content D:\ServerName.txt) -ne '' -join ','

@(Get-Content D:\ServerName.txt) returns the input lines as an array[1] of strings, from which
-ne '' then removes empty lines, and the result of which -join joins with separator ,


[1] Get-Content D:\ServerName.txt would return a scalar (single string), if the input file happened to contain only 1 line, because PowerShell generally reports a single output object as itself rather than as a single-element array when pipeline output is collected.
Because of that, @(...), the array-subexpression operator - instead of just (...) - is needed in the above command: it ensures that the output from Get-Command is treated as an array, because the -ne operator acts differently with a scalar LHS and returns a Boolean rather than filtering the LHS's elements: compare 'foo' -ne '' to @('foo') -ne ''.
By contrast, the @(...) is not necessary if you pass the result (directly) to -join (which simply is a no-op with a scalar LHS):
(Get-Content D:\ServerName.txt) -join ','

Upvotes: 1

tommymaynard
tommymaynard

Reputation: 2152

Best as I can tell, you're attempting to comma separate your servers. I'd skip the Foreach construct myself and simply use the join operator.

$ServerList = Get-Content -Path 'D:\ServerName.txt'
$ServerList -join ','

This can be done in a single statement, as well.

$ServerList = (Get-Content -Path 'D:\ServerName.txt') -join ','

Tommy

Upvotes: 1

Related Questions