【PowerShell】フルパスからファイル名を取得方法

PowerShell

Split-Pathを使う方法

Split-Pathはパスから特定要素を抽出
-Leafでは末端の要素を取得

$File_path  = "‪C:\Users\user\Desktop\test.xlsx"  
$fileName = Split-Path $File_path -Leaf
Write-Host $fileName

.NETのPathクラスを使う方法

System.IO.PathクラスのGetFileNameメソッドを使い、指定したパス文字列のファイル名と拡張子を返す方法

$File_path  = "‪C:\Users\user\Desktop\test.xlsx"  
$fileName = [System.IO.Path]::GetFileName("$File_path")
Write-Host $fileName

Get-ChildItemを使う方法

Get-ChildItemを使う。そのNameプロパティを参照してファイル名を取得

$File_path  = "‪C:\Users\user\Desktop\test.xlsx" 
$fileInfo = Get-ChildItem -Path $File_path
$fileName = $fileInfo.Name
Write-Host $fileName

コメント