要使用它启动脚本,Start-Job需要在提供给 的数组中使用正确的参数顺序-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 = 'gmail@hchucknoris.com'
)
Run Code Online (Sandbox Code Playgroud)
我们想知道如何检索$LogFolder和中设置的默认值$ScriptAdmin?
我的尝试似乎找不到它:
$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
}
Run Code Online (Sandbox Code Playgroud)
如果我们有默认值,我们可以Start-Job更灵活地使用,以防我们只想使用强制参数来启动作业$ScriptAdmini,但希望保留该值$LogFolder而不是用空字符串将其删除,因为我们需要尊重顺序或论点。
您可以使用 Ast 解析来实现此目的:
$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
}
Run Code Online (Sandbox Code Playgroud)
有关其他潜在的抽象语法树类型,请参阅System.Management.Automation.Language 命名空间。
| 归档时间: |
|
| 查看次数: |
1083 次 |
| 最近记录: |