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.

1
  • What's provoking the question? Commented Jul 28, 2021 at 15:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.