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.
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.