You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell中获取带波浪线~的DOS格式文件夹短名称

获取PowerShell中文件夹的DOS短名称

针对带空格的文件夹(如"Shared Files"),可以通过以下几种PowerShell函数动态获取其DOS约定的短名称(如shared~1),无需硬编码:

方法1:通过WMI/CIM查询实现

利用Windows的WMI类Win32_Directory直接读取文件夹的短名称属性:

function Get-DosShortName {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Path
    )

    if (-not (Test-Path -Path $Path)) {
        throw "指定路径不存在: $Path"
    }

    # 转义路径中的反斜杠以适配WMI查询语法
    $escapedPath = $Path.Replace('\','\\')
    $dirInstance = Get-CimInstance -ClassName Win32_Directory -Filter "Name='$escapedPath'"
    
    return $dirInstance.ShortName
}

# 使用示例
$workingDir = Join-Path -Path $PSScriptRoot -ChildPath "."
$sharedFilesPath = Join-Path -Path $workingDir -ChildPath "Shared Files"
$shortName = Get-DosShortName -Path $sharedFilesPath
# 输出结果示例: shared~1
Write-Host "DOS短名称: $shortName"

方法2:借助FileSystemObject COM对象

通过Windows脚本宿主的COM对象获取短名称,实现逻辑更简洁:

function Get-DosShortName {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Path
    )

    if (-not (Test-Path -Path $Path)) {
        throw "指定路径不存在: $Path"
    }

    $fso = New-Object -ComObject Scripting.FileSystemObject
    $folder = $fso.GetFolder($Path)
    
    return $folder.ShortName
}

# 使用示例
$workingDir = Join-Path -Path $PSScriptRoot -ChildPath "."
$sharedFilesPath = Join-Path -Path $workingDir -ChildPath "Shared Files"
$shortName = Get-DosShortName -Path $sharedFilesPath
Write-Host "DOS短名称: $shortName"

方法3:调用cmd的dir命令解析

通过dir /x命令输出提取短名称,无需依赖COM或WMI:

function Get-DosShortName {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Path
    )

    if (-not (Test-Path -Path $Path)) {
        throw "指定路径不存在: $Path"
    }

    $parentDir = Split-Path -Path $Path -Parent
    $folderName = Split-Path -Path $Path -Leaf

    # 调用cmd获取带短名称的目录列表并过滤目标文件夹
    $dirOutput = cmd /c "dir `"$parentDir`" /x | findstr /i `"$folderName`""
    # 从输出中提取短名称(位于第二列)
    $shortName = $dirOutput -split '\s+' | Select-Object -Index 1
    
    return $shortName
}

# 使用示例
$workingDir = Join-Path -Path $PSScriptRoot -ChildPath "."
$sharedFilesPath = Join-Path -Path $workingDir -ChildPath "Shared Files"
$shortName = Get-DosShortName -Path $sharedFilesPath
Write-Host "DOS短名称: $shortName"

调用老式程序的示例

获取短名称后,可直接拼接路径调用老式程序:

$oldProgramPath = Join-Path -Path $workingDir -ChildPath "$shortName\old_app.exe"
& $oldProgramPath

内容的提问来源于stack exchange,提问作者hillcountry99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:25:27