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 1:

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

Solution 2:

Use .net:

[System.IO.Path]::GetFileName("c:\foo.txt") returns foo.txt. [System.IO.Path]::GetFileNameWithoutExtension("c:\foo.txt") returns foo

Solution 3:

Using the BaseName in Get-ChildItem displays the name of the file and and using Name displays the file name with the extension.

$filepath = Get-ChildItem "E:\Test\Basic-English-Grammar-1.pdf"

$filepath.BaseName

Basic-English-Grammar-1

$filepath.Name

Basic-English-Grammar-1.pdf

Solution 4:

You could get the result you want like this.

$file = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$a = $file.Split("\")
$index = $a.count - 1
$a.GetValue($index)

If you use "Get-ChildItem" to get the "fullname", you could also use "name" to just get the name of the file.

Solution 5:

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