Skip to content

Instantly share code, notes, and snippets.

@AnonymerNiklasistanonym
Created February 14, 2025 10:53
Show Gist options
  • Save AnonymerNiklasistanonym/0d039d84da0cabb30ce6f07809a38bf2 to your computer and use it in GitHub Desktop.
Save AnonymerNiklasistanonym/0d039d84da0cabb30ce6f07809a38bf2 to your computer and use it in GitHub Desktop.
Invoke elevated command from within a PowerShell script
function Invoke-ElevatedCommand {
param (
[string]$Command
)
$ExpandedCommand = "Write-Host `"Command: `"$Command`"; $Command; Read-Host 'Press Enter to exit window and continue'"
Write-Host "Invoke-ElevatedCommand: `"$Command`""
$process = Start-Process powershell.exe -Verb RunAs -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command `"$ExpandedCommand`"" -PassThru
$process.WaitForExit()
}
# Examples
$FilePath = "your file path"
Invoke-ElevatedCommand -Command "Remove-Item -Path '$FilePath' -Force"
$FileDir = "your file dir"
Invoke-ElevatedCommand -Command "New-Item -ItemType Directory -Path '$FileDir'"
$FilePathInSource = "your input file path"
$FilePathInTarget = "your output file path"
Invoke-ElevatedCommand -Command "Copy-Item -Path '$FilePathInSource' -Destination '$FilePathInTarget' -Force"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment