2

I have a function which returns PSCustomObject, like this:

Function Get-Data {
  # ...
  [PSCustomObject]@{
    Url = $Url
    Id = $Id
  }
}

Later on, I call this function like this:

$data = Get-Data

And then I'd like to output formatted string including property values of that object. The closest result to what I want is output with the line below:

Write-Host "$($data.Url)|$($data.Id)|OK"

The problem is a whitespace after the first | character.

Where does it come from? How to get rid of it the proper way?

Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
Yan Sklyarenko
  • 31,557
  • 24
  • 104
  • 139

3 Answers3

2

You could either call .Trim() to each string (as Mathias mentioned). Or you can replace any whitespace character using a regex:

Write-Host ("$($data.Url)|$($data.Id)|OK" -replace '\s*') 
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
  • I've finally figured out the issue. I'll describe it in my answer in more details. I'm accepting your answer since it correctly addresses the problem described in the question. Thank you! – Yan Sklyarenko Apr 11 '17 at 12:18
1

Apparently, it was all hidden in the details of that Get-Data method, which I airily ignored...

Before creating that custom object, the method does a number of REST API calls, and the output of one of those calls was not assigned to a variable, nor was it "Out-Null"-ed. As a result, the real custom object returned was the one made of that web response plus my explicitly created custom object as a property.

Looks like PowerShell tried hard to infer the types for me, but it failed to manage those leading whitespaces...

Hope this can save someone some time.

Yan Sklyarenko
  • 31,557
  • 24
  • 104
  • 139
  • Thank you! Had the exact same issue, because I, inside a function, printed a not-yet defined variable, which then, paired with the return statement, apparently introduced a separating whitespace...! – Johny Skovdal Aug 10 '17 at 13:22
0

Just wanted to add another tip on this topic as I was running into it as well. Even though I was seeing no leading whitespace in the return value from within the function. Once the value was returned, there was an extra leading white space. I found that a previous line of Write-Verbose code that was outputing an object's content was messing me up

Write-Verbose $obj | fl * | Out-String

I added parenthesis around the output, which fixed my issue Write-Verbose ($obj | fl * | Out-String)

I'm guessing something about the Out-String part was messing with the function's pipeline and causing the extra white space to get added to the beginning of the string value the function was returning

JScott
  • 73
  • 2
  • 9