Invoke-AsAdmin-Module.psm1
<#
.SYNOPSIS Executes a specified script block with administrative privileges. .DESCRIPTION The Invoke-AsAdmin function allows you to run a PowerShell script block with administrative privileges. It creates a temporary script file to execute the provided script block and captures the output in a temporary text file. Optionally, you can provide credentials to run the script as a specific user. .PARAMETER Script The script block to be executed with administrative privileges. This parameter is mandatory. .PARAMETER Credential Optional credentials to run the script as a specific user. This parameter accepts a PSCredential object. .EXAMPLE $script = { Get-Process } Invoke-AsAdmin -Script $script Runs the Get-Process command with administrative privileges. .EXAMPLE $script = { Get-Process } $credential = Get-Credential Invoke-AsAdmin -Script $script -Credential $credential Runs the Get-Process command with administrative privileges using the provided credentials. .OUTPUTS Writes the output of the executed script block to the console. .NOTES The function creates a temporary PowerShell script file and a temporary output text file. Both files are deleted after execution. .AUTHOR Jonas Schmitz - skouts e.K. #> Function Invoke-AsAdmin { param( [Parameter(Mandatory=$True)] [ScriptBlock]$Script, [Parameter()] [System.Management.Automation.PSCredential]$Credential ) # Pfad zur temporären Skriptdatei $tempScriptPath = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), [System.IO.Path]::GetRandomFileName() + ".ps1") # Pfad zur Ausgabe-Textdatei $outputFile = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), [System.IO.Path]::GetRandomFileName() + ".txt") # Inhalt des temporären Skripts $scriptContent = @" Start-Transcript -Path '$outputFile' $($Script.ToString()) Stop-Transcript "@ # Schreiben des Skriptinhalts in die temporäre Datei $scriptContent | Out-File -FilePath $tempScriptPath -Encoding UTF8 # Erstellen des Prozessstart-Info-Objekts $startInfo = New-Object System.Diagnostics.ProcessStartInfo $startInfo.FileName = "powershell.exe" $startInfo.Arguments = "-NoProfile -ExecutionPolicy Bypass -File `"$tempScriptPath`"" $startInfo.UseShellExecute = $false $startInfo.CreateNoWindow = $true if ($Credential) { $startInfo.UserName = $Credential.UserName $startInfo.Password = $Credential.Password $startInfo.Domain = $Credential.GetNetworkCredential().Domain } $process = [System.Diagnostics.Process]::Start($startInfo) $process.WaitForExit() # Überprüfen, ob die Ausgabedatei erstellt und befüllt wurde if (Test-Path $outputFile) { Write-Host "Ausgabedatei wurde erstellt:" Get-Content $outputFile } else { Write-Host "Ausgabedatei wurde nicht erstellt." } # Löschen des temporären Skripts Remove-Item -Path $tempScriptPath -Force # Löschen der Ausgabedatei, wenn sie erstellt wurde (optional) Remove-Item -Path $outputFile -Force } |