Created
February 14, 2025 10:53
-
-
Save AnonymerNiklasistanonym/0d039d84da0cabb30ce6f07809a38bf2 to your computer and use it in GitHub Desktop.
Invoke elevated command from within a PowerShell script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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