2017-06-05 113 views
0

我要拆分的路徑,只是保存文件名test.xls在一個新的變量獲取從一個文件的完整路徑只有文件名

$namearray = "C:\Users\z003m\Desktop\Service_Tickets\automationscript\vbs\Newfolder\test.xls" 
+1

'$ newVariable =拆分路徑$ namearray -Leaf' – gms0ulman

+1

過得好到'$ namearray'?如果你使用'Get-ChildItem',你可以從中得到文件名... – Nick

+0

@ gms0ulman你應該發表你的建議作爲答案,因爲它是最好的方法。 –

回答

6

推薦使用內置Split-Path

$newVariable = Split-Path $namearray -Leaf 
1

您還可以使用.NET實現

[System.IO.Path]分路小命令

快10倍
[System.IO.Path]::GetFileName('c:\myFile.txt') 
# result myFile.txt 

[System.IO.Path]::GetFileNameWithoutExtension('c:\myFile.txt') 
# result myFile 

性能比較:50000項

[System.IO.Path]::GetFileName(...) Average: 12,84143 

Split-Path       Average: 113,537884 
+0

這是一個很糟糕的方式來做到這一點,使用'分離路徑'效率更高。 –

+0

我改變了我的帖子。你能刪除你的評論嗎? – k7s5a

+0

'Split-Path'支持多個PowerShell提供程序;它不僅分割文件系統名稱,而且分割多個路徑。這將解釋爲什麼它(毫無意義,除非你每秒劃分數千個名字)比.NET實現慢。 –