Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unnecessary space in output when using Write-Host

Tags:

powershell

When I use Write-Host within a Foreach-Object, I get an unnecessary space in the output.

write-host "http://contoso.com/personal/"$_.ADUserName

Output:

http://contoso.com/personal/ john.doe

How can I remove the space before john? Trim does not work because there is no space in $_.ADUserName

like image 520
Peter Molnar Avatar asked Apr 20 '17 23:04

Peter Molnar


People also ask

Why should you not use Write-host?

It's always been recommended to avoid using Write-Host because it outputs only to the console and not to any of the standard output streams. As of PowerShell 5.0, Write-Host is just a wrapper for Write-Information and thus outputs to the standard output streams similar to the other Write-* cmdlets.

What is true about Write-host command?

Write-Host sends the objects to the host. It does not return any objects. However, the host displays the objects that Write-Host sends to it.

What is the difference between the Write-host and the Write-output commands?

In a nutshell, Write-Host writes to the console itself. Think of it as a MsgBox in VBScript. Write-Output , on the other hand, writes to the pipeline, so the next command can accept it as its input.

What is Write-output in PowerShell?

Write-Output sends objects to the primary pipeline, also known as the "output stream" or the "success pipeline." To send error objects to the error pipeline, use Write-Error . This cmdlet is typically used in scripts to display strings and other objects on the console.


1 Answers

This is happening because Write-Host is considering your constant string and your object to be two separate parameters -- you aren't actually joining the strings together the way you're calling it. Instead of calling it this way, actually concatenate the strings:

write-host "http://contoso.com/personal/$($_.ADUserName)"

or

write-host ("http://contoso.com/personal/" + $_.ADUserName)

or

write-host ("http://contoso.com/personal/{0}" -f $_.ADUserName)
like image 85
Dave Markle Avatar answered Oct 01 '22 12:10

Dave Markle