mark
mark

Reputation: 62876

How can I make PowerShell concatenate some command output and a string?

Observe:

PS Z:\dev> echo $(hg root)\windows
Z:\dev
\windows
PS Z:\dev>

I want to see Z:\dev\windows. Trying to quote $(hg root) does not help.

EDIT

Observe:

PS Z:\dev\windows\nc> echo $((hg root).Trim())\Windows
Z:\dev
\Windows
PS Z:\dev\windows\nc> $r = (hg root).Trim()
PS Z:\dev\windows\nc> echo $r\Windows
Z:\dev\Windows
PS Z:\dev\windows\nc> $r = hg root
PS Z:\dev\windows\nc> echo $r\Windows
Z:\dev\Windows
PS Z:\dev\windows\nc>

I would like to narrow the scope of my question. I am specifically interested in a one line solution, since this is how I am used to do it in Bash (echo `hg root`/windows just works)

EDIT 2

PS Z:\dev> Write-Host $(hg root)\windows
Z:\dev \windows
PS Z:\dev> Write-Host $((hg root).Trim())\windows
Z:\dev \windows
PS Z:\dev>

Write-Host is no good either - note the space between Z:\dev and \windows in the output.

Upvotes: 2

Views: 5355

Answers (2)

Richard
Richard

Reputation: 109140

It looks like the result of hg root includes a newline.

Two possibilities:

echo $((hg root).Trim())\Windows

$r = (hg root).Trim()
echo $r\Windows

(I would tend to use the latter as it is clearer, especially in scripts.)

Additional (based on comment, and extra in question):

It is not clear why the first approach doesn't work, as I don't have Mercurial (I assume) installed. I tried:

echo Foo$((Out-String -InputObject "Bar`n").Trim())Bax

which gives a one line result:

FooBarBax

My first thought would be to look very carefully at the output of hg root (for example, via a hex dump, such as PSCX's Format-Hex).

For a single line solution, recall that the grammar is $(‹statement list›), so the two lines of my second approach can be combined with a pipeline:

echo "$(hg root | % {$_.Trim()})\Windows"

(also putting the whole argument to Write-Host (echo being an alias) into quotes to make things a little clearer). Or even using two statements:

echo "$($a = hg root; $a.Trim())\Windows"

Upvotes: 2

halfer
halfer

Reputation: 20487

(Posted answer on behalf of the question author).

Apparently, I need to get more sleep:

PS Z:\dev> echo "$(hg root)\windows"
Z:\dev\windows
PS Z:\dev>

Please, accept my apologies for this question - I had forgotten to try the quotes around the whole expression.

Upvotes: 0

Related Questions