当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 如何在 PowerShell 中获取不带扩展名的文件名

作者:精品下载站 日期:2024-12-14 05:11:31 浏览:11 分类:玩电脑

如何在 PowerShell 中获取不带扩展名的文件名


最近,我的一位客户要求我编写一个 PowerShell 脚本来查找文件夹中不带扩展名的文件名。我尝试了不同的方法。在本 PowerShell 教程中,我将解释如何使用多种方法在 PowerShell 中获取不带扩展名的文件名。

要在 PowerShell 中获取不带扩展名的文件名,可以使用 FileInfo 对象的 BaseName 属性,该属性可以通过使用 Get-Item cmdlet 获取。或者,使用 .NET Framework 中的 [System.IO.Path]::GetFileNameWithoutExtension() 方法来实现更具编程性的方法。另一种选择是使用带有 -LeafBase 参数的 Split-Path cmdlet,它直接输出不带扩展名的文件名。

使用 Get-Item 和 BaseName 属性

在 PowerShell 中获取不带扩展名的文件名的最简单方法是使用 Get-Item cmdlet,然后访问 BaseName 属性。文件对象的 BaseName 属性包含不带扩展名的文件名。这是完整的 PowerShell 脚本。

# Define the full path of the file
$filePath = "C:\MyFolder\Users.txt"

# Get the file name without the extension
$fileNameWithoutExtension = (Get-Item $filePath).BaseName

# Display the file name
Write-Output $fileNameWithoutExtension

这将输出 Users,这是不带 .txt 扩展名的文件名。

我使用 VS code 执行了上面的脚本,您可以在下面的屏幕截图中清楚地看到输出:

[玩转系统] 如何在 PowerShell 中获取不带扩展名的文件名

使用 System.IO.Path 类方法

您还可以使用 .NET Framework 类和方法在 PowerShell 中获取不带扩展名的文件名。 您可以使用System.IO.Path 类及其方法GetFileNameWithoutExtension。这个 .NET Framework 方法可以直接在 PowerShell 中使用,如下所示

# Define the full path of the file
$filePath = "C:\example\sample.txt"

# Get the file name without the extension using System.IO.Path class
$fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($filePath)

# Display the file name
Write-Output $fileNameWithoutExtension

此脚本还将返回 sample 作为不带扩展名的文件名。

使用拆分路径 Cmdlet

PowerShell 的 Split-Path cmdlet 也可用于隔离不带扩展名的文件名。此 cmdlet 旨在操作路径字符串,并且可以与 -LeafBase 参数一起使用。

# Define the full path of the file
$filePath = "C:\MyFolder\Users.txt"

# Use Split-Path with -LeafBase to get the file name without the extension
$fileNameWithoutExtension = Split-Path $filePath -LeafBase

# Display the file name
Write-Output $fileNameWithoutExtension

执行上述 PowerShell 脚本后,它将向我们显示与第一种方法类似的输出。

使用正则表达式

您还可以使用正则表达式,PowerShell 可以匹配模式并使用 -replace 运算符提取不带扩展名的文件名。

# Define the full path of the file
$filePath = "C:\example\sample.txt"

# Use regex to remove the extension from the file name
$fileNameWithoutExtension = $filePath -replace "\.[^.]+$"

# Extract just the file name without the path
$fileNameWithoutExtension = [System.IO.Path]::GetFileName($fileNameWithoutExtension)

# Display the file name
Write-Output $fileNameWithoutExtension

这将输出示例,去除目录路径和文件扩展名。

结论

在本教程中,我们探索了几种使用 PowerShell 获取不带扩展名的文件名的方法,例如使用 Get-ItemSplit-Path 等本机 cmdlet ,或 .NET Framework 方法,例如来自 System.IO.Path 的方法。

Get-ItemBaseName cmdlet 易于阅读和使用,可在 PowerShell 中获取不带扩展名的文件名。

我希望您现在能够完整了解如何使用 PowerShell 获取不带扩展名的文件名。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯