从路径中提取文件名

Extract the filename from a path

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

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

现在我写了这段代码来获取文件名。只要文件夹级别没有改变,这就可以正常工作。但如果文件夹级别已更改,则需要重写此代码。我正在寻找一种使其更灵活的方法,例如无论文件夹级别如何,代码始终可以提取文件名。

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

你可以得到你想要的结果。

$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

使用:

[System.IO.Path]::GetFileName("c:\foo.txt")returnsfoo.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 显示文件名,使用 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(内置 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

适用于相对路径和绝对路径