2727 When specified, removes any trailing directory separator (backslash) from
2828 paths, including drive letters.
2929
30+ . PARAMETER ExpandEnvironmentVariable
31+ Replaces the name of each environment variable embedded in the specified string
32+ with the string equivalent of the value of the variable.
33+ Each environment variable must be quoted with the percent sign character (%).
34+
3035 . EXAMPLE
3136 Format-Path -Path 'C:/MyFolder/'
3237
6570
6671 Returns '/var/log' on Linux/macOS or '\var\log' on Windows.
6772 Unix-style absolute paths are normalized to use the system's directory separator.
73+
74+ . EXAMPLE
75+ Format-Path -Path '%WinDir%\SubFolder' -ExpandEnvironmentVariable
76+
77+ Returns the path with the environment variable expanded, e.g., 'C:\Windows\SubFolder'
6878#>
6979function Format-Path
7080{
@@ -82,17 +92,29 @@ function Format-Path
8292
8393 [Parameter ()]
8494 [System.Management.Automation.SwitchParameter ]
85- $NoTrailingDirectorySeparator
95+ $NoTrailingDirectorySeparator ,
96+
97+ [Parameter ()]
98+ [System.Management.Automation.SwitchParameter ]
99+ $ExpandEnvironmentVariable
86100 )
87101
88- if ($Path -match ' ^(?:[a-zA-Z]:|\\\\)' )
102+ # Use local variable so it always exists.
103+ $normalizedPath = $Path
104+
105+ if ($ExpandEnvironmentVariable )
106+ {
107+ $normalizedPath = [System.Environment ]::ExpandEnvironmentVariables($normalizedPath )
108+ }
109+
110+ if ($normalizedPath -match ' ^(?:[a-zA-Z]:|\\\\)' )
89111 {
90112 # Path starts with a Windows drive letter, normalize to backslashes.
91- $normalizedPath = $Path -replace ' /' , ' \'
113+ $normalizedPath = $normalizedPath -replace ' /' , ' \'
92114 }
93115 else
94116 {
95- $normalizedPath = $Path -replace ' [\\|/]' , [System.IO.Path ]::DirectorySeparatorChar
117+ $normalizedPath = $normalizedPath -replace ' [\\|/]' , [System.IO.Path ]::DirectorySeparatorChar
96118 }
97119
98120 # Remove trailing backslash if parameter is specified and path is not just a drive root.
0 commit comments