我有一个here字符串,我想在参数块之后注入一个语句。挑战是,我不知道Here-String的结构,它应该适用于各种Here-Strings(有和没有param块)。
例如:
$scriptBlock = @'
Param (
[Parameter(Mandatory=$false)][string]$param1,
[Parameter(Mandatory=$false)][string]$param2,
[Parameter(Mandatory=$false)][switch]$param3
)
Write-Output ('param1: {0}' -f $param1)
Write-Output ('param2: {0}' -f $param2)
Write-Output ('param3: {0}' -f $param3)
Get-Location
'@
invoke-expression "$scriptBlock"
在param块之后我想注入以下语句。
Set-Location C:\temp
结果应如下所示:
$scriptBlock = @'
Param (
[Parameter(Mandatory=$false)][string]$param1,
[Parameter(Mandatory=$false)][string]$param2,
[Parameter(Mandatory=$false)][switch]$param3
)
Set-Location C:\temp
Write-Output ('param1: {0}' -f $param1)
Write-Output ('param2: {0}' -f $param2)
Write-Output ('param3: {0}' -f $param3)
Get-Location
'@
invoke-expression "$scriptBlock"
答案 0 :(得分:1)
怎么样?
$scriptcontent = [System.Management.Automation.Language.Parser]::ParseInput($scriptblock, [ref]$null, [ref]$null)
$paramblock = $scriptcontent.ParamBlock
if ($paramblock) {
$scriptblock = $scriptblock.Replace($paramblock.Extent.Text, $paramblock.Extent.Text + "`nSet-Location C:\temp;`n")
}
$scriptblock
Param (
[Parameter(Mandatory=$false)][string]$param1,
[Parameter(Mandatory=$false)][string]$param2,
[Parameter(Mandatory=$false)][switch]$param3
)
Set-Location C:\temp;
Write-Output ('param1: {0}' -f $param1)
Write-Output ('param2: {0}' -f $param2)
Write-Output ('param3: {0}' -f $param3)
Get-Location