Search code examples
powershellsubstring

What is the equivalent of str.Substring in PowerShell?


I'm making a simple compiling tool as a way to practice PS, and I need to extract a part of the string into another variable. For example:

[string]$Filepath = "C:/Users/xxx/Projects/file.cpp" (I need the last part of the string)

Since I'm a beginner at PS, is there a way to possibly do this without using a regex?

I tried the -match thing but I'm not looking for any specific value, I just need everything after the last "/".


Solution

  • To answer the question contained in your post's title:

    What is the equivalent of str.Substring in PowerShell?

    PowerShell offers virtually unlimited access to all .NET APIs, so you're free to call the System.String type's .Substring() directly; e.g.:

    # -> 'file.cpp'
    "C:/Users/xxx/Projects/file.cpp".Substring(22)
    

    I just need everything after the last "/".

    Similarly, you can use the .NET .Split() method to split a string by a given, verbatim character and combine it with PowerShell's enhanced indexing to allow you to reference elements from the end, using negative indices, notably [-1] to refer to the last element of an array (as well as other .NET types implementing the System.Collections.IList interface).

    # -> 'file.cpp'
    "C:/Users/xxx/Projects/file.cpp".Split('/')[-1]
    

    PowerShell itself offers the -split operator, whose RHS, the split criterion, is interpreted as a regex by default (with / that doesn't make a difference):

    # -> 'file.cpp'
    ("C:/Users/xxx/Projects/file.cpp" -split '/')[-1]
    

    See this answer for why using -split over .Split() is generally preferable, considering the tradeoffs involved.


    Another option is to use PowerShell's regex-based -replace operator; the following uses a regex to match everything up to the last / character and - due to not specifying a substitution operand - effectively removes what was matched, leaving only what comes after the last /:

    # -> 'file.cpp'
    "C:/Users/xxx/Projects/file.cpp" -replace '^.*/'
    

    For a comprehensive but concise summary of -replace, see this answer.


    Finally, only with separators / and \, you can use the Split-Path cmdlet's -Leaf parameter, taking advantage of the fact that PowerShell recognizes \ and / interchangeably as path (directory) separators:

    # -> 'file.cpp'
    Split-Path -Leaf "C:/Users/xxx/Projects/file.cpp"