我最近聽到某人說,Windows 管理員應該使用 CMD 登入腳本而不是 BAT 登入腳本,因為運行或執行速度更快。顯然 BAT 腳本是出了名的慢。
我做了一些谷歌搜索,但找不到任何證據來支持這一說法。我只是想知道這是否是一個神話,或者是否有人可以了解更多?
答案1
儘管腳本的運行方式存在BAT
一些CMD
差異此處討論(憑藉功績錘子的評論),命令被解析並執行相繼因此記住下一個命令的偏移量(0
在起點)並再次從磁碟開啟腳本檔案以執行下一個命令。
1000
腳本中的命令意味著1000
對相同檔案進行磁碟操作(開啟-讀取-關閉)。為了準確起見,我不會透露線但關於命令。
那是BAT
和CMD
腳本緩慢的真正根源。
為了證明:運行一個簡單的範例腳本忽略提示刪除檔案;腳本type
本身會:
==> 725431.cmd
725431.cmd script. Please follow instructions.
Press any key to continue . . .
Please erase d:\bat\725431.cmd file prior to continuing.
Press any key to continue . . .
you didn't erase d:\bat\725431.cmd file prior to continuing?
---
@echo off
echo %~nx0 script. Please follow instructions.
pause
echo Please erase %~f0 file prior to continuing.
pause
echo you didn't erase %~f0 file prior to continuing?
echo ---
type "%~f0"
運行上面的腳本觀察提示刪除檔案;The batch file cannot be found
錯誤表示批次解析器無法取得下一個echo
命令:
==> 725431.cmd
725431.cmd script. Please follow instructions.
Press any key to continue . . .
Please erase d:\bat\725431.cmd file prior to continuing.
Press any key to continue . . .
The batch file cannot be found.
為了完整起見,以下是標準檔案系統錯誤訊息:
==> type 725431.cmd
The system cannot find the file specified.
相反,類似的(例如)PowerShell
腳本被緩存在記憶體中。再次運行範例腳本忽略提示先刪除檔案;腳本type
本身會:
PS D:\PShell> D:\PShell\SF\725431.ps1
D:\PShell\SF\725431.ps1 script. Please follow instructions.
Press Enter to continue...:
Please erase D:\PShell\SF\725431.ps1 file prior to continuing.
Press Enter to continue...:
you didn't erase D:\PShell\SF\725431.ps1 file prior to continuing?
---
echo "$PSCommandPath script. Please follow instructions."
pause
echo "Please erase $PSCommandPath file prior to continuing."
pause
echo "you didn't erase $PSCommandPath file prior to continuing?"
echo "---"
Get-Content $PSCommandPath
運行腳本觀察提示刪除該檔案。這樣做將表明後者echo
已Get-Content
緩存在記憶體中:
PS D:\PShell> D:\PShell\SF\725431.ps1
D:\PShell\SF\725431.ps1 script. Please follow instructions.
Press Enter to continue...:
Please erase D:\PShell\SF\725431.ps1 file prior to continuing.
Press Enter to continue...:
you didn't erase D:\PShell\SF\725431.ps1 file prior to continuing?
---
Get-Content : Cannot find path 'D:\PShell\SF\725431.ps1' because it does not ex
ist.
At D:\PShell\SF\725431.ps1:8 char:1
+ Get-Content $PSCommandPath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (D:\PShell\SF\725431.ps1:String)
[Get-Content], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetCo
ntentCommand