如何在PowerShell中获取没有扩展名的文件路径?

时间:2013-02-08 10:33:36

标签: powershell

我在powershell 2.0脚本中的变量中有一个绝对路径。我想剥离扩展,但保留完整的路径和文件名。最简单的方法吗?

因此,如果我在名为C:\Temp\MyFolder\mytextfile.fake.ext.txt

的变量中有$file

我想返回

C:\Temp\MyFolder\mytextfile.fake.ext

5 个答案:

答案 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)

https://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension%28v=vs.110%29.aspx

答案 4 :(得分:0)

无论$filestring还是FileInfo对象:

(Get-Item $file).BaseName
相关问题