Search code examples
powershellssissql-server-agent

Powershell-Command to download a file with admin rights


I try do download a file via a powershell command. The command I use is simple:

Start-BitsTransfer  -Source  'https://download.com/file.zip' -Destination 'E:\test\file.zip'

I can run the command in PS succesfully. But now I want to run it with elevated rights. So I gooogled and found this solution:

There it says the command should be:

Start-Process powershell.exe -Verb Runas -ArgumentList "-Command & {get-process}"

So I tried adjusting it for my use case:

 Start-Process powershell.exe -Verb Runas -ArgumentList "-Command & {Start-BitsTransfer  -Source  'https://download.com/file.zip' -Destination 'E:\test\file.zip'}"

But all is does is open a new PS-Window and closing it right after. Where is my mistake?


Solution

  • You can change to this

    Start-Process powershell.exe -Verb Runas -ArgumentList "& {Start-BitsTransfer  -Source  'https://download.com/file.zip' -Destination 'E:\test\file.zip'}"
    

    Note the window will close after the execution completes. If you would like to see the output/errors (such as what would be shown in your non working example) just add another command to pause.

    Start-Process powershell.exe -Verb Runas -ArgumentList "& {Start-BitsTransfer  -Source  'https://download.com/file.zip' -Destination 'E:\test\file.zip';pause}"
    

    & is used to invoke a command. It's useful for executing strings or scriptblocks. It runs in a child runspace.

    & 'Get-Host'
    & 'Write-Host' Hello -Fore Green
    & {Write-Host Goodbye -Fore Cyan}
    

    ; is used to separate different commands on the same line.

    & {$name = 'Doug';Write-Host Hello $name}
    

    You can also use a period to invoke a scriptblock in the current runspace. In the previous command the $name variable would be empty in the callers scope where the following command would leave the variable defined.

    & {$name = 'Doug';Write-Host Hello $name}
    $name # empty as it all happens in the child scope
    

    vs

    . {$name = 'Doug';Write-Host Hello $name}
    $name # populated because it's brought into the caller's scope