windows - 批处理文件中的错误处理

标签 windows powershell batch-file rename

我正在编写一个脚本来自动执行一些任务。本质上,它只是重命名文件(如果存在)。然而,这些文件对于其他一些软件的运行至关重要。如果重命名文件失败,或者找不到文件,我希望它说出它是哪个文件。但是,REN 命令在失败时的描述性并不强。我知道如果失败,它会将 ERRORLEVEL 提高到 1。我可以从失败中获取其他信息吗,例如文件名?或者它只是成功还是失败?

运行此程序的机器是 Windows 7 及更高版本,因此如果需要,powershell 也是一个选项,但我更喜欢批处理。

谢谢

最佳答案

Ken White在对该问题的评论中指出,cmd.exeren 命令发出的错误消息包含文件名涉及(s)

PowerShell 相比之下,提供详细错误消息,确实包含文件名
采用以下示例脚本:

# Create helper sample files.
$tempFiles = "$env:TEMP\foo", "$env:TEMP\bar"
$null = New-Item -Type File $tempFiles

# Try to rename a nonexistent item.
Rename-Item \no\such -NewName foo

# Try to rename to a file that already exists.
Rename-Item $env:TEMP\foo -NewName bar

# Clean up the sample files.
Remove-Item $tempFiles

如果将上述内容保存到 *.ps1 文件并运行它(假设您有 permitted scripts to run ),您将看到以下错误输出:

Rename-Item : Cannot rename because item at '\no\such' does not exist.
At C:\Users\jdoe\Desktop\pg\pg.ps1:8 char:5
+     Rename-Item \no\such -NewName foo
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand

Rename-Item : Cannot create a file when that file already exists.
At C:\Users\jdoe\Desktop\pg\pg.ps1:11 char:5
+     Rename-Item $env:TEMP\foo -NewName bar
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (C:\Users\jdoe\AppData\Local\Temp\foo:String) [Rename-Item], IOException
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

虽然输出很详细,但它确实包含所有相关信息,您甚至可以通过自动 $Error 变量以编程方式检查它,该变量包含所有错误按时间倒序在 session 中报告($Error[0] 包含最近的最近错误)。

并非如此,默认情况下,当这些错误发生时,PowerShell 脚本将继续运行,因为它们被视为非终止

  • 让脚本立即中止的最简单方法是使用 $ErrorActionPreference= 'Stop' 行启动脚本。

  • 或者,您可以在每个命令的基础上使用-ErrorAction Stop

运行Get-Help about_Preference_VariablesGet-Help about_CommonParameters了解更多信息。

关于windows - 批处理文件中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44189614/

相关文章:

c++ - OpenGL 上的多线程渲染

json - 使用 Powershell 将 JSON 保存到带有 pretty-print 的文件

powershell - 使用 PowerShell 编写哈希表脚本

regex - 使用Powershell匹配文本文件中所有出现的模式

batch-file - 扩展变量不求值

Windows 8.1 : "IsUserAnAdmin" returns false even though UAC is off and the user a member of "administrators"

windows - gvim 先前在兼容模式下发出的命令

batch-file - 管道到 BATCH 脚本中的 CALL 函数

Python 将字符串输入与现有字典匹配的简单方法

c++ - 使用具有不同编译器版本的 C++ DLL