PowerShell: Remove Everything After Last Forward Slash


You can use the following basic syntax in PowerShell to remove everything in a string after (and including) the last forward slash:

$my_path -replace '/[^/]*$', ''

This particular example removes everything in the string variable named $my_path after (and including) the last forward slash in the string.

Note that this syntax uses the -replace operator to match the text between the last forward slash in a string to the end ( $ ) of the string and replace all of this text with nothing.

This has the effect of removing everything after and including the last forward slash.

The following example shows how to use this syntax in practice.

Example: Remove Everything After Last Forward Slash in PowerShell

Suppose that we have the following string saved in a variable named $my_path:

  • c:/users/bobbi/teams, players, coaches

Suppose that we would like to remove everything after and including the last forward slash in the string.

We can use the following syntax to do so:

$my_path = 'c:/users/bobbi/teams, players, coaches'
$my_path -replace '/[^/]*$', ''

The following screenshot shows how to use this syntax in practice:

PowerShell replace everything after last forward slash in string

This returns the following string:

  • c:/users/bobbi

Notice that all text after and including the last forward slash in the string has been removed.

Note that you could also use the following syntax if you’d like to remove everything after but not including the last forward slash:

$my_path = 'c:/users/bobbi/teams, players, coaches'
$my_path -replace '[^/]*$', ''

The following screenshot shows how to use this syntax in practice:

This returns the following string:

  • c:/users/bobbi/

Notice that all text after but not including the last forward slash in the string has been removed.

Feel free to use whichever method you prefer.

Note: You can find the complete documentation for the -replace operator in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Text with Wildcard
PowerShell: How to Replace Special Characters in String

Leave a Reply