将param块后的语句注入PowerShell Here-String

时间:2017-09-16 10:47:14

标签: powershell

我有一个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"

1 个答案:

答案 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