2

I regularly use the the echo $PWD > /dev/clipboard in Git Bash to hardcode paths in my scripts but I find it quite annoying to have to run Git Bash to do this, I would really like to do that in powershell

The issue it that it seems that the output of echo $PWD (or really any environnement variables) makes weird thing with the clipboard

echo $pwd

outputs

Path
----
C:\ProgramData\chocolatey\bin

And if I try to put it in clipboard using echo $pwd | Set-Clipboard it just fails silently, it tries to add it but Windows straight up refuses (Office Clipboard says that it's an unsupported fornat, although it's just text)

Set-Clipboard -Value $pwd

Works but prepends the path with this annoying Path ----

Is there any way to have just the path like %cd% works in CMD but in Powershell?

Bassie
  • 9,529
  • 8
  • 68
  • 159
  • Note that you can examine a variable's type and its members (properties, methods) via the [`Get-Member`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-member) cmdlet. – mklement0 Dec 13 '20 at 14:29
  • As an aside: `$PWD` isn't an _environment_ variable, but a PowerShell specific [_automatic variable_](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Automatic_Variables). – mklement0 Dec 13 '20 at 15:13

1 Answers1

2

Try this

Set-Clipboard -Value $pwd.Path

Or you can use

$pwd.Path | clip

However see mklement0's comment

Note that if you pipe to clip.exe, a trailing newline is invariably added and with non-ASCII characters you'll run into encoding issues

Bassie
  • 9,529
  • 8
  • 68
  • 159
  • 2
    Nice; simpler: `"$pwd"`. Also, if you need a file-system-_native_ path - as opposed to one based on a _PowerShell_ drive, use `$pwd.ProviderPath`. Note that if you pipe to `clip.exe`, a trailing newline is invariably added and with non-ASCII characters you'll run into encoding issues - see [this answer](https://stackoverflow.com/a/15581127/45375). Given the obsolescence of the ISE (see next comment), I suggest not recommending it, at least not without a warning. – mklement0 Dec 13 '20 at 14:26
  • 1
    The PowerShell ISE is [no longer actively developed](https://docs.microsoft.com/en-us/powershell/scripting/components/ise/introducing-the-windows-powershell-ise#support) and [there are reasons not to use it](https://stackoverflow.com/a/57134096/45375) (bottom section), notably not being able to run PowerShell [Core] 6+. The actively developed editor that offers the best PowerShell development experience, across platforms, is [Visual Studio Code](https://code.visualstudio.com/), combined with its [PowerShell extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.PowerShell). – mklement0 Dec 13 '20 at 14:26
  • 2
    I'm already using VSCode extensively and won't switch to anything other anytime soon so I can only agree with you @mklement0, and thanks for the string trick – Nicolas Formichella Dec 13 '20 at 14:40