I'm working with a PowerShell script that utilizes Invoke-WebRequest from my local computer to attempt downloading a file directly onto a remote computer. However, I noticed that this method actually downloads the file to my local machine instead of the intended remote system. I'm not here to critique the design but I'm struggling to find any documentation addressing this behavior. Here's the relevant part of my script:
```powershell
Invoke-Command -ComputerName "RemoteComputerName" -FilePath ".download-file.ps1"
```
The script within `download-file.ps1` looks like this (it's not fully complete):
```powershell
Invoke-WebRequest -Uri $url -OutFile $destinationPath
```
3 Answers
Consider modifying your `download-file.ps1` to be a PowerShell ScriptBlock instead. You can set this up by hardcoding it or referencing it like this:
```powershell
Invoke-Command -ScriptBlock ([scriptblock]::Create((Get-Content ".download-file.ps1")))
```
This might change how the script executes on the remote computer.
I hit the same issue! To get around this, I first download the file to my local machine, then I create a temporary PowerShell drive on the remote PC. After that, I copy the file over to the remote drive and then to the target location. Here’s a quick rundown of how I do it:
```powershell
$url = "https://packages.vmware.com/wsone/AirwatchAgent.msi"
$localPath = "C:tempAirwatchAgent.msi"
Invoke-WebRequest -Uri $url -OutFile $localPath
# Create temp PSDrive for the remote machine
try {
New-PSDrive -Name "RemoteTemporary" -PSProvider FileSystem -Root "\$remoteHostC$" -Credential $credential
Copy-Item -Path $localPath -Destination "RemoteTemporary:tempAirwatchAgent.msi"
Write-Host "MSI file copied successfully."
} Catch {
Write-Host "Unable to copy MSI file to remote machine."
}
# Clean up the PSDrive
Remove-PSDrive -Name "RemoteTemporary"
```
This method works like a charm!
Is this assuming the remote machine is air-gapped? I’d probably just modify the script to use curl and download files directly instead. In my Linux experience, using SSH to execute curl or wget on a remote VM doesn't have this problem of tunneling through the local PC.
The file should ideally be downloading to 'RemoteComputerName.' Can you share what your `$destinationPath` looks like?
$destinationPath is set to `C:FolderSu Folder`.
I think the behavior would still be similar for ScriptBlocks.