从路径中提取文件名

我想从下面的路径提取文件名:

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)
170234 次浏览

你可以像这样得到你想要的结果。

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

如果您使用“ Get-ChildItem”来获取“ fullname”,那么您也可以使用“ name”来获取文件的名称。

如果你同意包括扩展,这应该做你想要的。

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

使用 :

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

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

在 Get-ChildItem 使用 BaseName 显示文件名,而 Using Name 显示扩展名为。

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


$filepath.BaseName


Basic-English-Grammar-1


$filepath.Name


Basic-English-Grammar-1.pdf
Get-ChildItem "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
|Select-Object -ExpandProperty Name

只是为了完成上面的使用.Net 的答案。

在这段代码中,路径存储在 %1参数中(这是在注册表中引用转义后写入的: \"%1\")。要检索它,我们需要 $arg(内置参数)。别忘了 $FilePath的引用。

# Get the File path:
$FilePath = $args
Write-Host "FilePath: " $FilePath


# Get the complete file name:
$file_name_complete = [System.IO.Path]::GetFileName("$FilePath")
Write-Host "fileNameFull :" $file_name_complete


# Get File Name Without Extension:
$fileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension("$FilePath")
Write-Host "fileNameOnly :" $fileNameOnly


# Get the Extension:
$fileExtensionOnly = [System.IO.Path]::GetExtension("$FilePath")
Write-Host "fileExtensionOnly :" $fileExtensionOnly

你可以试试这个:

[System.IO.FileInfo]$path = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
# Returns name and extension
$path.Name
# Returns just name
$path.BaseName

使用通配符查找文件并获取文件名:

Resolve-Path "Package.1.0.191.*.zip" | Split-Path -leaf
$file = Get-Item -Path "c:/foo/foobar.txt"
$file.Name

使用相对路径和绝对路径