Skip to content

Instantly share code, notes, and snippets.

@qoli
Created June 6, 2025 06:40
Show Gist options
  • Save qoli/3d81709d0ab8641bfc0728b1951ff552 to your computer and use it in GitHub Desktop.
Save qoli/3d81709d0ab8641bfc0728b1951ff552 to your computer and use it in GitHub Desktop.
param (
# Accept command parts as an array
[Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)]
[string[]]$CommandParts
)
# Check if command parts were provided
if (-not $CommandParts) {
Write-Host "Error: Please provide the command parts as arguments after the script path."
Write-Host "Example: powershell.exe -File .\your_script.ps1 part1 part2 part3"
exit 1
}
# Reconstruct the full command string from the parts
# Quote parts containing spaces to handle them correctly if needed later,
# though Set-Content should handle the full string fine.
# Method compatible with older PowerShell versions:
$command = ($CommandParts | ForEach-Object { if ($_ -match '\s') { "'$($_ -replace "'", "''")'" } else { $_ } }) -join ' '
Write-Verbose "Reconstructed command: $command" -Verbose
# Generate unique names for the task and temporary script file
$taskName = "temp_ps_runner_$(Get-Random)"
$tempScriptPath = Join-Path $env:TEMP "temp_ps_script_$(Get-Random).ps1"
Write-Verbose "Using temporary task name: $taskName" -Verbose
Write-Verbose "Using temporary script path: $tempScriptPath" -Verbose
# --- Main logic within a try/finally block to ensure cleanup ---
try {
# Write the reconstructed command to the temporary script file
try {
Write-Verbose "Value of reconstructed `$command before writing to file: '$command'" -Verbose
# Use Set-Content to write the full reconstructed command string
Set-Content -Path $tempScriptPath -Value $command -Encoding UTF8 -NoNewline -ErrorAction Stop
Write-Verbose "Command successfully written to $tempScriptPath using Set-Content" -Verbose
# Print the content of the temp file for debugging
$tempContent = Get-Content -Path $tempScriptPath -Raw -ErrorAction SilentlyContinue
Write-Verbose "Content written to temporary file '$tempScriptPath':`n--- START --`n$tempContent`n--- END ---" -Verbose
} catch {
Write-Error "Failed to write command to temporary file '$tempScriptPath'. Error: $_"
exit 1
}
# Construct the command string for schtasks /tr to execute the temp file
$commandTemplate = 'powershell.exe -ExecutionPolicy Bypass -NoProfile -NonInteractive -File \"{0}\"'
$scheduledCommand = $commandTemplate -f $tempScriptPath
Write-Verbose "Command string for schtasks /tr: $scheduledCommand" -Verbose
# --- Execute schtasks commands ---
schtasks /Create /F /tn $taskName /tr "$scheduledCommand" /sc once /st 00:00:00 /RL LIMITED
if ($LASTEXITCODE -ne 0) {
Write-Error "Failed to create scheduled task '$taskName'. schtasks exit code: $LASTEXITCODE"
exit $LASTEXITCODE
}
Write-Verbose "Task '$taskName' created successfully." -Verbose
schtasks /run /tn $taskName
if ($LASTEXITCODE -ne 0) {
Write-Error "Failed to run scheduled task '$taskName'. schtasks exit code: $LASTEXITCODE"
exit $LASTEXITCODE
}
Write-Verbose "Task '$taskName' run initiated." -Verbose
Start-Sleep -Seconds 2
schtasks /delete /F /tn $taskName
if ($LASTEXITCODE -ne 0) {
Write-Warning "Failed to delete scheduled task '$taskName'. schtasks exit code: $LASTEXITCODE"
} else {
Write-Verbose "Task '$taskName' deleted successfully." -Verbose
}
} finally {
# --- Cleanup ---
if (Test-Path $tempScriptPath) {
Write-Verbose "Cleaning up temporary script file: $tempScriptPath" -Verbose
Remove-Item $tempScriptPath -Force -ErrorAction SilentlyContinue
}
$taskCheck = schtasks /query /tn $taskName 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Verbose "Ensuring task '$taskName' is deleted during cleanup..." -Verbose
schtasks /delete /F /tn $taskName /RL LIMITED
if ($LASTEXITCODE -ne 0) {
Write-Warning "Could not delete task '$taskName' during final cleanup."
}
}
}
Write-Verbose "Script finished." -Verbose
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment