silverspr
silverspr

Reputation: 25

Unwanted space in substring using powershell

I'm fairly new to PS: I'm extracting fields from multiple xml files ($ABB). The $net var is based on a pattern search and returns a non static substring on line 2. Heres what I have so far:

    $ABB = If ($aa -eq $null ) {"nothing to see here"} else {
    $count = 0
    $files = @($aa)
      foreach ($f in $files)
      {
         $count += 1

         $mo=(Get-Content -Path $f )[8].Substring(51,2) 
         (Get-Content -Path $f | Select-string -Pattern $lf -Context 0,1) |  ForEach-Object {
         $net = $_.Context.PostContext
         $enet = $net -split "<comm:FieldValue>(\d*)</comm:FieldValue>"
         $enet = $enet.trim()}

         Write-Host "$mo-nti-$lf-$enet" "`r`n"

       }}

The output looks like this: 03-nti-260- 8409. Note the space prefacing the 8409 which corresponds to the $net variable. I haven't been able to solve this on my own, my approach could be all wrong. I'm open to any and all suggestions. Thanks for your help.

Upvotes: 0

Views: 595

Answers (2)

AdminOfThings
AdminOfThings

Reputation: 25031

Since your first characters in the first line of $net after $net = $_.Context.PostContext contains the split characters, a blank line will output as the first element of the output. Then when you stringify output, each split output item is joined by a single space.

You need to select lines that aren't empty:

$enet = $net -split "<comm:FieldValue>(\d*)</comm:FieldValue>" -ne ''

Explanation:

-Split characters not surrounded by () are removed from the output and the remaining string is split into multiple elements from each of those matched characters. When a matched character starts or ends a string, a blank line is output. Care must be taken to remove those lines if they are not required. Trim() will not work because Trim() applies to a single string rather than an array and will not remove empty string.

Adding -ne '' to the end of the command, removes empty lines. It is just an inline boolean condition that when applied to an array, only outputs elements where the condition is true.

You can see an example of the blank line condition below:

123 -split 1

23

123 -split 1 -ne ''
23

Upvotes: 1

postanote
postanote

Reputation: 16116

Just use a -replace to get rid of any spaces For example:

'03-nti-260- 8409' -replace '\s'
<#
# Results
03-nti-260-8409
#>

Upvotes: 0

Related Questions