0

I'm trying to write a powershell script that will download an exe from a specified URL (passed through as a parameter at the time of calling the script)

The code I have:

Param(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true)]
[String]
$cwdl
)

Start-Job -Name WebReq -ScriptBlock { Invoke-WebRequest $cwdl -OutFile "C:\MYFILEPATH\cw.exe" }
Wait-Job -Name WebReq

If I replace the $cwdl with "mypathtoexefile" then it works. But with the $cwdl variable it does nothing. I've even tried statically setting $cwdl as either $cwdl = 'mypathtoexefile' and $cwdl = "mypathtoexefile" but nothing I've tried is allowing the Invoke-WebRequest to resolve the filepath if I'm using a variable, regardless of if it's generated by the parameter.

mklement0
  • 382,024
  • 64
  • 607
  • 775
kurtis452
  • 3
  • 2
  • 1
    Are you sure `$cwdl` has the correct content inside the scriptblock? Try to prefix the variable with `$script:`. – Alex_P Mar 08 '20 at 20:36
  • I removed the scriptblock and you're right. I need that script block in place though as the rest of my scipt needs to wait for the download to finish downloading. Where to I add the prefix? As in: -ScriptBlock { Invoke-WebRequest $Script:$cwdl ... ? – kurtis452 Mar 08 '20 at 20:56
  • 2
    @Alex_P: It's not `$script:` that's required here, but `$using:`, given that the script block is executed in a _background job_ - see [this answer](https://stackoverflow.com/a/57281995/45375). – mklement0 Mar 08 '20 at 21:15

1 Answers1

0

Example 8: Pass input to a background job This example uses the $input automatic variable to process an input object. Use Receive-Job to view the job's output. PowerShell

Copy Start-Job -ScriptBlock { Get-Content $input } -InputObject "C:\Servers.txt" Receive-Job -Name Job45 -Keep

Server01 Server02 Server03 Server04 Start-Job uses the ScriptBlock parameter to run Get-Content with the $input automatic variable. The $input variable gets objects from the InputObject parameter. Receive-Job uses the Name parameter to specify the job and outputs the results. The Keep parameter saves the job output so it can be viewed again during the PowerShell session.

Lumir J.
  • 66
  • 1
  • 9
  • 1
    Generally, please quote your source and [format your code and sample input/output properly](http://meta.stackexchange.com/a/22189/248777). In this particular case, the example you quote uses an awkward, rarely used technique to pass data to the background job: instead of passing an _argument_ with `-ArgumentList` (or more simply directly referencing the caller's variable value with `$using:`), the example uses _pipeline input_, via `-InputObject`, which must be accessed via automatic variable `$Input` inside the script block. – mklement0 Mar 08 '20 at 21:31