windows命令行一些常見問題

  1. 帶空格的路徑
    如果命令路徑有空格,需要加”“來運行,否則會有“C:\Program”命令找不到的錯誤。
    • 經常有一些程序的啓動腳本寫的不完善,需要自己去手動去加“”在變量上。
    • 如果是需要在命令行中使用的命令,儘量單獨放在某目錄下,這樣可以最大程度減少路徑問題引發的錯誤。
"C:\Program Files\java\jdk\bin\java" -version
#或者
cd C:\Program^ Files
cd "%ProgramFiles%\batch.cmd"
cd "%ProgramFiles(x86)%\batch.cmd"

2.junction 軟連接
A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, and a junction can link directories located on different local volumes on the same computer. Otherwise, junctions operate identically to hard links. Junctions are implemented through reparse points.

C:\Windows\system32>mklink /J "C:\Program_Files" "C:\Program Files"
# ouptut Junction created for C:\Program_Files <<===>> C:\Program Files

3.%~dp0的使用
- %0-9是輸入到batchfile的輸入參數佔位符;
- %後面跟一個~,可以在參數前加一個修飾符;
- d表示驅動器,如C、D盤符;
- p表示當前文件的路徑;
例如,新建一個test.bat

@echo off
rem 打印當前路徑,與%CD%效果相同
pushd %~dp0../ #展開當前路徑並改變當前路徑爲上一層

引用stackoverflow上的一段解釋如下

The %~dp0 (that’s a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file.
The variables %0-%9 refer to the command line parameters of the batch file. %1-%9 refer to command line arguments after the batch file name. %0 refers to the batch file itself.
If you follow the percent character (%) with a tilde character (~), you can insert a modifier(s) before the parameter number to alter the way the variable is expanded. The d modifier expands to the drive letter and the p modifier expands to the path of the parameter.
Example: Let’s say you have a directory on C: called bat_files, and in that directory is a file called example.bat. In this case, %~dp0 (combining the d and p modifiers) will expand to C:\bat_files.
And a more clear reference from here:
%CmdCmdLine% will return the entire command line as passed to CMD.EXE
%* will return the remainder of the command line starting at the first command line argument (in Windows NT 4, %* also includes all leading spaces)
%~dn will return the drive letter of %n (n can range from 0 to 9) if %n is a valid path or file name (no UNC)
%~pn will return the directory of %n if %n is a valid path or file name (no UNC)
%~nn will return the file name only of %n if %n is a valid file name
%~xn will return the file extension only of %n if %n is a valid file name
%~fn will return the fully qualified path of %n if %n is a valid file name or directory

參考
windows命令索引 https://ss64.com/nt/
robvanderwoude’s Scripting Pages http://www.robvanderwoude.com/batchstart.php

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章