0

In order to deliver the current working directory adress to a program. I need to provide the directory Path separated by forward slashes /. The program does not accept a string containing backslashes.

Currently, the pwd-Command delivers the following: C:\testdir1\testdir2

I want the following string: C:/testdir1/testdir2

Is there an easy way to transform this directory adress in a powershell script?

Thank you in advance.

Sandwichnick
  • 1,379
  • 6
  • 13

2 Answers2

3

Use the -replace operator[1] to perform (invariably global) string replacements (since it is regex-based, a verbatim \ must be escaped as \\); the automatic $PWD variable contains the PowerShell session's current location (which, if the underlying provider is the FileSystem provider, is a directory):

$PWD -replace '\\', '/'

If you want to ensure that the resulting path is a file-system-native path (one not based on PowerShell-only drives):

$PWD.ProviderPath -replace '\\', '/'

If there's a chance that the current location is from a provider other than the file-system (e.g., a registry-based drive such as HKLM:).

(Get-Location -PSProvider FileSystem).ProviderPath -replace '\\', '/'

[1] In this simple case, calling the [string] type's .Replace() method is an alternative, but the -replace operator is more PowerShell-idiomatic and offers superior functionality. This answer contrasts the two.

mklement0
  • 382,024
  • 64
  • 607
  • 775
1

Fast code but seems to works as expected

# Original path
$Path = "C:\testdir1\testdir2"
Write-Host "Original Path is:" $Path
#Replace \ by /
$Changed = $Path -replace '\\', '/'
Write-Host "changed path:" $Changed

Output

Original Path is: C:\testdir1\testdir2
changed path: C:/testdir1/testdir2
LEFBE
  • 125
  • 1
  • 9