0

I have made a PowerShell script that takes a few parameters and this script needs be launched as admin. I only have 2 types of parameters in my script: switch and string:

Param (
    [Parameter(
        Mandatory = $false,
    )][switch]$SkipUpdate = $true,
    [Parameter(
        Mandatory = $false,
    )][switch]$UserReport = $true,
    [Parameter(
        Mandatory = $false,
    )][switch]$ComputerReport = $true,
    [Parameter(
        Mandatory = $false,
    )][string]$SearchScope = ""
)

The script is launched like this:

.\MyScript.ps1 -Param1:$false -Param2 "Some text"

Using Google, I quickly found this code:

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) {
    Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" $PSCommandArgs" -Verb RunAs
    exit
}

It's asking for admin rights but it forgets all parameters once relaunched as admin

I've also found another script on this website It looked very interesting but it's not working (code is maybe outdated)

Any help would be appreciated!

Cool34
  • 9
  • 1
  • Unfortunately, a robust self-elevation implementation with parameter passthrough and working-directory preservation is quite complex and has inherent limitations. The linked duplicate is a reusable best-effort approach. Situationally you may get away with simpler implementations. – mklement0 May 15 '23 at 12:32
  • As an aside: There is no automatic `$PSCommandArgs` variable, but there is an [automatic `$PSBoundParameters` variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Automatic_Variables#psboundparameters), which is a dictionary containing the bound parameters and their values, but the challenge lies in encoding them for use via `Start-Process`. – mklement0 May 15 '23 at 12:33

0 Answers0