[英]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.