Home > database >  How to split the last string in PowerShell
How to split the last string in PowerShell

Time:10-13

I have a column that look something like this in my csv file

SharePoint\user\Documents\2021_Changes_v2048.csv
SharePoint\user\Documents\ACB Client Repair\Client MSI's\CE1.3\CE16098\CE16098-Global\Agree.hta
SharePoint\user\Documents\ACB Client Repair\Client MSI's\AgentSetup_881.msi

I'm just wondering how can I get only the last string like this

2021_Changes_v2048.csv
Agree.hta
AgentSetup_881.msi

I've try like this but some reason it's not working yet

$result = "SharePoint\mz1tl6_nam_corp_gm_com\Documents\2020_Changes_v512.csv"
$result.split("\",3)[-2]

Not really sure how to get the string only after the last backslash .

CodePudding user response:

The two easiest options are either Split-Path -Leaf or an API call to [IO.Path]::GetFileName(...). Assuming you will want objects out of these for future export, here is how it looks:

$paths = @"
SharePoint\user\Documents\2021_Changes_v2048.csv
SharePoint\user\Documents\ACB Client Repair\Client MSI's\CE1.3\CE16098\CE16098-Global\Agree.hta
SharePoint\user\Documents\ACB Client Repair\Client MSI's\AgentSetup_881.msi
"@ -split '\r?\n'

$paths | Select-Object @{ N='FileName'; E={ [IO.Path]::GetFileName($_) }}
$paths | Select-Object @{ N='FileName'; E={ Split-Path $_ -Leaf }}

CodePudding user response:

Your file does not look like a CSV, if thats the whole content its simply a textfile, so you can do:

#load file
$content = gc [path]

#split at '\' and output last string
$content | %{($_ -split '\\')[-1]}

#output
2021_Changes_v2048.csv
Agree.hta
AgentSetup_881.msi

CodePudding user response:

You could use Split-Path built-in function.

Refer to https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/split-path?view=powershell-7.2#example-2-display-file-names

  • Related