问题描述
要使用 Start-Job
启动脚本,需要在提供给 -ArgumentList
的数组中使用正确的参数顺序.
For launching scripts with Start-Job
it is required to use the correct order of parameters within the array provided to -ArgumentList
.
考虑这个脚本:
# $script = c:\myScripts.ps1
Param (
[Parameter(Mandatory)]
[String]$ScriptName,
[Parameter(Mandatory)]
[String]$Path,
[Parameter(Mandatory)]
[String[]]$MailTo,
[String]$LogFolder = "\\$env:COMPUTERNAME\Log",
[String]$ScriptAdmin = '[email protected]'
)
我们想知道如何检索 $LogFolder
和 $ScriptAdmin
中设置的默认值?
We would like to know how it is possible to retrieve the default values set in $LogFolder
and $ScriptAdmin
?
我似乎无法找到它的尝试:
My attempt where I can't seem to find it:
$scriptParameters = (Get-Command $script).Parameters.GetEnumerator() |
Where-Object { $psBuildInParameters -notContains $_.Key }
foreach ($p in $scriptParameters.GetEnumerator()) {
'Name: {0} Type: {1} Mandatory: {2} DefaultValue: x' -f $p.Value.Name, $p.Value.ParameterType, $p.Value.Attributes.Mandatory
}
如果我们有默认值,我们可以更灵活地使用 Start-Job
,以防我们只想使用强制参数启动作业并说 $ScriptAdmini
,但是想要将值保留在 $LogFolder
中,而不是用空字符串将其清空,因为我们需要尊重顺序或参数.
If we have the default value we can use Start-Job
more flexible in case we want to start a job with only the mandatory parameters and say $ScriptAdmini
, but want to keep the value in $LogFolder
and not blank it out with an empty string because we need to respect the order or the arguments.
推荐答案
您可以为此使用 Ast 解析:
You can use Ast parsing for this:
$script = 'c:\myScripts.ps1'
# Parse the script file for objects based on Ast type
$parsed = [System.Management.Automation.Language.Parser]::ParseFile($script,[ref]$null,[ref]$null)
# Extract only parameter ast objects
$params = $parsed.FindAll({$args[0] -is [System.Management.Automation.Language.ParameterAst]},$true)
$params | Foreach-Object {
$name = $_.Name.VariablePath.ToString()
$type = $_.StaticType.FullName
# Convoluted because the property values themselves present strings rather than booleans where the values are $false or false
$mandatory = [bool]($_.Attributes | where {$_.NamedArguments.ArgumentName -eq 'Mandatory'} |% {$_.NamedArguments.Argument.SafeGetValue()})
$DefaultValue = $_.DefaultValue.Value
"Name: {0} Type: {1} Mandatory: {2} DefaultValue: {3}" -f $name,$type,$mandatory,$DefaultValue
}
参见 System.Management.Automation.Language Namespace 用于其他潜在的抽象语法树类型.
See System.Management.Automation.Language Namespace for other potential abstract syntax tree types.
这篇关于PowerShell 中有没有办法获取脚本参数的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!