我最近听别人说,Windows 管理员应该使用 CMD 登录脚本而不是 BAT 登录脚本,因为 CMD 登录脚本运行或执行速度更快。显然,BAT 脚本的速度非常慢。
我搜索了一下,但找不到任何证据来支持这一说法。我只是想知道这是不是谣言,或者是否有人对此有更多了解?
答案1
尽管脚本的运行方式存在一些BAT
差异CMD
,这里讨论(凭借功绩Hammer 的评论)命令被解析并执行相继在此记住下一个命令偏移量(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