我在powershell 2.0脚本中的变量中有一个绝对路径。我想剥离扩展,但保留完整的路径和文件名。最简单的方法吗?
因此,如果我在名为C:\Temp\MyFolder\mytextfile.fake.ext.txt
$file
我想返回
C:\Temp\MyFolder\mytextfile.fake.ext
答案 0 :(得分:19)
如果是[string]
类型:
$file.Substring(0, $file.LastIndexOf('.'))
如果是[system.io.fileinfo]
类型:
join-path $File.DirectoryName $file.BaseName
或者你可以施展它:
join-path ([system.io.fileinfo]$File).DirectoryName ([system.io.fileinfo]$file).BaseName
答案 1 :(得分:11)
以下是我更喜欢的最佳方式和其他示例:
$FileNamePath
(Get-Item $FileNamePath ).Extension
(Get-Item $FileNamePath ).Basename
(Get-Item $FileNamePath ).Name
(Get-Item $FileNamePath ).DirectoryName
(Get-Item $FileNamePath ).FullName
答案 2 :(得分:4)
# the path
$file = 'C:\Temp\MyFolder\mytextfile.fake.ext.txt'
# using regular expression
$file -replace '\.[^.\\/]+$'
# or using System.IO.Path (too verbose but useful to know)
Join-Path ([System.IO.Path]::GetDirectoryName($file)) ([System.IO.Path]::GetFileNameWithoutExtension($file))
答案 3 :(得分:4)
您应该使用简单的.NET框架方法,而不是将路径部分拼凑在一起或进行替换。
PS> [System.IO.Path]::GetFileNameWithoutExtension($file)
答案 4 :(得分:0)
无论$file
是string
还是FileInfo
对象:
(Get-Item $file).BaseName