Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How call invoke-expression to pass arguments when calling a remote script in powershell? [duplicate]

My script content:

param (
    [string]$arg1 = "2.2.2",
    [string]$arg2 = "master" 
)

& {
Write-Host "show $arg1 and $arg2 .."
}

Then I want to call this script in remote machine via http.

Invoke-Expression (Invoke-Webrequest "https://x.x.x.x/myscript.ps1" -UseBasicParsing).Content

But I don't know how to pass parameters to the script. Like this?

Invoke-Expression (Invoke-Webrequest "https://x.x.x.x/myscript.ps1" -UseBasicParsing).Content -arg1 2.2.1 -arg2 dev 

How can help me? thanks!


If I do not pass arguments, the following commands are working fine.

Invoke-Expression (Invoke-Webrequest "https://x.x.x.x/myscript.ps1" -UseBasicParsing).Content
like image 484
ruki Avatar asked Jan 30 '26 08:01

ruki


1 Answers

Download the code, create a scriptblock from it, and provide the arguments when calling Invoke() on the scriptblock.

$script = Invoke-RestMethod -Uri 'https://gist.githubusercontent.com/gittorta/75838602b2712d49c44e85ea0bc179e9/raw/8392f437943f66d47731423b674b81bd74378e4b/myscript.ps1'
$sb = [scriptblock]::Create($script)
$arg1 = "test1"
$arg2 = "test2"

$sb.Invoke($arg1, $arg2)

Output

show test1 and test2 ..

Same command condensed into a one-liner

([scriptblock]::Create((Invoke-RestMethod -Uri 'https://gist.githubusercontent.com/gittorta/75838602b2712d49c44e85ea0bc179e9/raw/8392f437943f66d47731423b674b81bd74378e4b/myscript.ps1'))).Invoke("test1", "test2")
like image 171
Daniel Avatar answered Jan 31 '26 23:01

Daniel