powershellpowershell-2.0

Extract the filename from a path


I want to extract filename from below path:

D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv

Now I wrote this code to get filename. This working fine as long as the folder level didn't change. But in case the folder level has been changed, this code need to rewrite. I looking a way to make it more flexible such as the code can always extract filename regardless of the folder level.

($outputFile).split('\')[9].substring(0)

Solution

  • If you are ok with including the extension this should do what you want.

    $outputPath = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
    $outputFile = Split-Path $outputPath -leaf