繁体   English   中英

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

[英]Convert long filename to short filename (8.3) using cmd.exe

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

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

短.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 ...调用的单行?

还有另一个问题(如何获取 DOS 路径而不是 Windows 路径),但是该问题专门询问当前目录的路径。

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

将 filename.txt 替换为要转换为 8.3 的文件名

dir /x filename.txt

然后,您必须使用空格作为分隔符(正则表达式中的 \\s)分割结果。 然后带有 ~ 的值是您的短文件名。 如果您的文件名开头很短,那么您将找不到包含 ~ 的字符串。

这是一个示例,它在注册表中读取“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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM