powershell-从路径中提取文件名
我想从以下路径中提取文件名:
D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv
现在,我编写了这段代码来获取文件名。 只要文件夹级别没有变化,此方法就可以正常工作。 但是,如果文件夹级别已更改,则此代码需要重写。 我正在寻找一种使其更灵活的方法,例如,无论文件夹级别如何,代码始终可以提取文件名。
($outputFile).split('\')[9].substring(0)
7个解决方案
106 votes
如果您可以包含扩展名,那么它应该做您想要的。
$outputPath = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$outputFile = Split-Path $outputPath -leaf
Gordon answered 2020-01-28T22:18:12Z
37 votes
使用.net:
[System.IO.Path]::GetFileName("c:\foo.txt")返回foo.txt。[System.IO.Path]::GetFileNameWithoutExtension("c:\foo.txt")返回foo
angularsen answered 2020-01-28T22:18:36Z
9 votes
在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
Sudhir Tharayil answered 2020-01-28T22:18:56Z
3 votes
您可以像这样获得想要的结果。
$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”获取“全名”,也可以使用“ name”仅获取文件名。
David answered 2020-01-28T22:19:20Z
2 votes
只是为了完成使用.Net的答案。
在此代码中,路径存储在$FilePath自变量中(该参数写在注册表中的转义引用下:\"%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
J. Does answered 2020-01-28T22:19:45Z
1 votes
$(分割路径“ D:\ Server \ User \ CUST \ MEA \ Data \ In \ Files \ CORRECTED \ CUST_MEAFile.csv”-叶)
Iain answered 2020-01-28T22:20:05Z
1 votes
Get-ChildItem "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv" |Select-Object -ExpandProperty Name
Ian Kemp answered 2020-01-28T22:20:25Z