gpt4 book ai didi

validation - 如何自动检查 powershell 脚本文件的语法?

转载 作者:行者123 更新时间:2023-12-04 16:30:54 24 4
gpt4 key购买 nike

我想为一些生成 powershell 脚本的代码编写单元测试,然后检查脚本是否具有有效的语法。

在不实际执行脚本的情况下执行此操作的好方法是什么?

.NET 代码解决方案是理想的,但我可以通过启动外部进程使用的命令行解决方案就足够了。

最佳答案

您可以通过 Parser 运行您的代码并观察它是否引发任何错误:

# Empty collection for errors
$Errors = @()

# Define input script
$inputScript = 'Do-Something -Param 1,2,3,'

[void][System.Management.Automation.Language.Parser]::ParseInput($inputScript,[ref]$null,[ref]$Errors)

if($Errors.Count -gt 0){
Write-Warning 'Errors found'
}

这可以很容易地变成一个简单的函数:
function Test-Syntax
{
[CmdletBinding(DefaultParameterSetName='File')]
param(
[Parameter(Mandatory=$true, ParameterSetName='File', Position = 0)]
[string]$Path,

[Parameter(Mandatory=$true, ParameterSetName='String', Position = 0)]
[string]$Code
)

$Errors = @()
if($PSCmdlet.ParameterSetName -eq 'String'){
[void][System.Management.Automation.Language.Parser]::ParseInput($Code,[ref]$null,[ref]$Errors)
} else {
[void][System.Management.Automation.Language.Parser]::ParseFile($Path,[ref]$null,[ref]$Errors)
}

return [bool]($Errors.Count -lt 1)
}

然后使用像:
if(Test-Syntax C:\path\to\script.ps1){
Write-Host 'Script looks good!'
}

关于validation - 如何自动检查 powershell 脚本文件的语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43213624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com