我的应用程序允许用户输入将在以后运行的powershell脚本.有没有一种简单的方法可以在不运行PowerShell脚本的情况下验证它,这样当用户输入它时,程序可能会报告语法错误?
谢谢.
在PowerShell v2中,您拥有可以在不运行脚本的情况下处理脚本的tokenizer.查看类System.Management.Automation.PSParser和它的静态方法Tokenize:
http://msdn.microsoft.com/en-us/library/system.management.automation.psparser(v=vs.85).aspx
在v3中它变得更好,有完整的语言命名空间/ AST支持:
http://msdn.microsoft.com/en-us/library/system.management.automation.language(v=vs.85).aspx
HTH Bartek
我编写了一个函数来自动执行该过程:Test-PSScript,您可以在我的博客上找到它
#Requires -Version 2
function Test-PSScript
{
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias('PSPath','FullName')]
[System.String[]] $FilePath,
[Switch]$IncludeSummaryReport
)
begin
{
$total=$fails=0
}
process
{
$FilePath | Foreach-Object {
if(Test-Path -Path $_ -PathType Leaf)
{
$Path = Convert-Path –Path $_
$Errors = $null
$Content = Get-Content -Path $path
$Tokens = [System.Management.Automation.PsParser]::Tokenize($Content,[ref]$Errors)
if($Errors)
{
$fails+=1
$Errors | Foreach-Object {
$_.Token | Add-Member -MemberType NoteProperty -Name Path -Value $Path -PassThru | `
Add-Member –MemberType NoteProperty -Name ErrorMessage -Value $_.Message -PassThru
}
}
$total+=1
}
}
}
end
{
if($IncludeSummaryReport)
{
Write-Host "`n$total script(s) processed, $fails script(s) contain syntax errors."
}
}
}
Run Code Online (Sandbox Code Playgroud)