使用cmd.exe将长文件名转换为短文件名(8.3)

时间:2012-04-19 11:35:37

标签: windows batch-file command-line long-filenames short-filenames

我正在尝试在Windows上将长文件名转换为短文件名(8.3)。

带命令行参数的批处理文件按预期工作:

short.bat

@echo OFF
echo %~s1

调用short.bat C:\Documents and Settings\User\NTUSER.DAT会返回C:\DOCUM~1\USER\NTUSER.DAT

但是,我不喜欢为此添加额外的.bat文件。我宁愿用ruby脚本中的整个命令调用cmd.exe。 我怎么能这样做?

作为中间步骤,我尝试对批处理文件中的路径进行硬编码,但这不起作用:

short1.bat

@echo OFF
SET filename="C:\Documents and Settings\User\NTUSER.DAT"
echo %filename%
echo %~sfilename%

echo %filename%有效,但echo %~sfilename%出现以下错误:

The following usage of the path operator in batch-parameter
substitution is invalid: %~sfilename%

For valid formats type CALL /? or FOR /?

如果 short1.bat 有效,我该如何将其转换为可以使用cmd.exe \c ...调用的单行?

还有另一个问题(how to get DOS path instead of Windows path),但是有一个问题是专门询问当前目录的路径。

3 个答案:

答案 0 :(得分:41)

cmd /c for %A in ("C:\Documents and Settings\User\NTUSER.DAT") do @echo %~sA

答案 1 :(得分:4)

将filename.txt替换为要转换为8.3

的文件名
dir /x filename.txt

然后,您必须将空格分隔为空格作为分隔符(正则表达式中的\ s)。 那么带〜的值就是你的短文件名。如果您的文件名很短,那么您将找不到包含〜。

的字符串

答案 2 :(得分:0)

以下是在注册表中读取“ appdata \ local”文件夹的位置并将其转换为短路径的示例:

cls
@echo off
cd /d "%~dp0"
chcp 65001 >nul

for /f "skip=1" %%a in ('"wmic useraccount where name='%USERNAME%' get sid"') do (
    for %%b in (%%a) do set current_SID=%%b
)
set current_username=%USERNAME%
set current_userprofile=%USERPROFILE%

set key_to_read=HKEY_USERS\%current_SID%\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
set value_to_read=Local AppData
rem If value_to_read contains ? space(s) set tokens to 2+?
for /f "usebackq eol= tokens=3,* delims= " %%a in (`reg query "%key_to_read%" /v "%value_to_read%" 2^>nul ^| find "%value_to_read%"`) do (
    set value_type=%%a
    set data_read=%%b
)
set data_read=%data_read:USERPROFILE=current_userprofile%
call set "data_read=%data_read%"
set current_local_appdata=%data_read%

set current_local_appdata_temp=%current_local_appdata%\Temp
echo %current_local_appdata_temp%

for %%a in ("%current_local_appdata_temp%") do set "current_local_appdata_temp_short=%%~sa"
echo %current_local_appdata_temp_short%

pause
exit