Home > OS >  PowerShell - Get everything after the first "-"
PowerShell - Get everything after the first "-"

Time:12-04

I have the following code:

$TodayDate = Get-Date -Format "dd-MM-yyyy"
$Student = Student01 - Project 01-02 - $TodayDate

Write-Host -NoNewline -ForegroundColor White "$Student"; Write-Host -ForegroundColor Green " - was delivered!"

This script returns in the console:

Student01 - Project 01-02 - dd-MM-yyyy - was delivered

How is it possible to return only everything after the first "-"?, that is Project 01-02 - dd-MM-yyyy - was delivered?

I thought about using .split, but I couldn't make it work so that it returns everything after the first "-".

CodePudding user response:

Your problem boils down to wanting to remove a prefix from a string.

Given that the prefix to remove cannot be defined as a static, literal string, but is defined by the (included) first occurrence of a separator, you have two PowerShell-idiomatic options:

  • Use the -split operator, which allows you to limit the number of resulting tokens; if you limit them to 2, everything after the first separator is returned as-is; thus, the 2nd (and last) token (accessible by index [-1]) then contains the suffix of interest:

    $str = 'Student01 - Project 01-02 - dd-MM-yyyy - was delivered'
    
    # Split by ' - ', and return at most 2 tokens, then extract the 2nd (last) token.
    # -> 'Project 01-02 - dd-MM-yyyy - was delivered'
    ($str -split ' - ', 2)[-1]
    
  • Use the -replace operator, which (like -split by default) is regex-based, and allows you to formulate a pattern that matches any prefix up to and including the first separator, which can then be removed:

    $str = 'Student01 - Project 01-02 - dd-MM-yyyy - was delivered'
    
    # Match everything up to the *first* ' - ', and remove it.
    # Note that not specifying a *replacement string* (second RHS operator)
    # implicitly uses '' and therefore *removes* what was matched.
    # -> 'Project 01-02 - dd-MM-yyyy - was delivered'
    $str -replace '^. ? - '
    
    • For an explanation of the regex (^. ? - ) and the ability to experiment with it, see this regex101.com page.
  • Related