Search code examples
powershellazure-powershellpowershell-4.0powershell-remoting

How to split a string correctly in PowerShell


I have this string

"C:\Users\testinguser\OneDrive - Company\Desktop\Hello\Jobs\Testing-Online\_vti_history\101376\Shared Documents\Global PKI\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx"

I'm just wondering how can I split from \_ and get the result only like this

vti_history\101376\Shared Documents\Global JLN\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx

I've try using -split("\_") but it didn’t work.

$Path = "C:\Users\testinguser\OneDrive - Company\Desktop\Hello\Jobs\Testing-Online\_vti_history\101376\Shared Documents\Global JLN\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx"

$Result = $Path -split('\_')[2]

any help or suggestion would be really appreciated.


Solution

  • You can do this

    $myString = "C:\Users\testinguser\OneDrive - Company\Desktop\Hello\Jobs\Testing-Online\_vti_history\101376\Shared Documents\Global PKI\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx" -split "(\\_)"
    Write-Output $myString[2]
    

    Output : vti_history\101376\Shared Documents\Global PKI\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx