【问题标题】:How to make verification process in PowerShell?如何在 PowerShell 中进行验证过程?
【发布时间】:2020-01-02 08:07:43
【问题描述】:

我有 powershell 脚本。它有很多过程,例如获取内容,复制文件,重命名扩展文件,删除文件,附加文本。 我想对每个流程进行验证,所以一旦我得到正确的结果,我将继续下一个流程。例如,为了检查文件,我使用 Test-Path。有人告诉我,在 PowerShell 中使用哪种验证更好?

感谢您的建议。

【问题讨论】:

  • 从术语“验证”你的意思是“调试”?
  • 你要求的是很常见的东西。这确实是 PowerShell 101 的事情。如果您知道结果显示是什么,那么您正在考虑使用 If/Then 和或 Try/Catch 代码块来获取您期望并希望对其采取行动的结果,然后还有其他几个选项,例如参数验证等,所有其中在 MS 文档站点、TechNet、MSDN 上,甚至在 MS 技术社区和 Youtube 上都有详细记录。只需搜索“PowerShell 验证”。你的脚本中有很多事情要做,所以这不是一个简单的单行/函数类型的东西。
  • 建议的答案听起来都可以满足您的要求,真的很基本。如果您正在寻找人工验证以继续通过脚本,那么您可以提示用户在屏幕上继续使用 Write-Host "Continue? (Y/N) 然后 $response = Read - 主持并为 Y 或 N 的答案设置一些事情发生。

标签: powershell


【解决方案1】:

您可以添加-WhatIf 参数来调试任何cmdlet。您还可以使用Try..Catch 块处理任何错误和异常。 E.G

Try  {
  Get-Content "C:\foo.txt" -ErrorAction Stop
}
Catch {
  # The statements put here will be executed if any error was caught in try block
}

您可以使用以下方法捕获特定错误:

Try  {
  Get-Content "C:\foo.txt" -ErrorAction Stop
}
Catch [System.Management.Automation.ItemNotFoundException] {
  # The statements put here will be executed if file not found
  # Any exception can be placed in the [] braces
  # ErrorAction Common parameter is used to pass the errors to catch block and halt script on error
  # You can remove that if you don't want to halt script on error
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 2018-05-11
    • 2014-05-20
    • 2021-12-04
    相关资源
    最近更新 更多