Search code examples
powershelltrim

Powershell TRIM() is removing extra character


I'm attempting to remove the "\MOSS2013" instance name from my SQL Server instance "WSFCSQLN1\MOSS2013"

This works:

$primaryReplicaGEN = $wsfcsqln2.AvailabilityGroups.PrimaryReplicaServerName
$primaryReplica = $PrimaryReplicaGEN.TRIM("\GEN")

$primaryReplica shows WSFCSQLN1

$primaryReplicaGEN shows WSFCSQLN1\GEN

This does not work:

$primaryReplicaMOSS2013 = $wsfcsqln1MOSS2013.AvailabilityGroups.PrimaryReplicaServerName
$primaryReplica = $PrimaryReplicaMOSS2013.TRIM("\MOSS2013")

$primaryReplica shows WSFCSQLN

$primaryReplicaMOSS2013 shows WSFCSQLN1\MOSS2013

Notice the replica name is missing the 1 at the end even though I did not choose to trim it. Why is it trimming the 1 for this particular string object? How can I force it to trim the correct characters.


Solution

  • Trim() turns the string argument into a [char[]] and removes any of those characters from both ends of the string.

    If you just want to grab the server name, use the -split operator and then discard the instance name:

    $ServerName = 'WSFCSQLN1\MOSS2013' -split '\\' |Select-Object -First 1
    

    or

    $ServerName,$null = 'WSFCSQLN1\MOSS2013' -split '\\'