2

I if a strings, which contains a powershell script block:

$scriptBlock = 'Param (
    [string]$param1,
    [string]$param2,
    [switch]$param3
)
Write-Output ('param1: {0}' -f $param1)
Write-Output ('param2: {0}' -f $param2)
Write-Output ('param3: {0}' -f $param3)'

Inside a second string I have the arguments for the script block.

$arguments = '-param1 "param1Value" -param2 "param2Value" -param3'

My question is how can I invoke the script block with the aruments string?

1
  • 1
    Why do you have the arguments in a single string? How did you obtain them in the first place? Commented Apr 16, 2017 at 12:18

1 Answer 1

1

Your $scriptblock string assignment is syntactically invalid, use a here-string to avoid having to escape the 's:

$scriptBlock = @'
Param (
    [string]$param1,
    [string]$param2,
    [switch]$param3
)
Write-Output ('param1: {0}' -f $param1)
Write-Output ('param2: {0}' -f $param2)
Write-Output ('param3: {0}' -f $param3)
'@

You could define a function with the contents of the $scriptblock string:

$functionName = "__command$(Get-Random)"
New-Item -Path function:\ -Name $functionName -Value $scriptBlock

Then invoke it using Invoke-Expression:

$result = Invoke-Expression "$functionName $arguments"

And clean up:

Remove-Item function:\$functionName
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Works like a charm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.