Archive for March, 2008

Invoke executable from powershell at low (idle) priority

March 11, 2008

Howdy, this blog is primarily to store tech goodies that I wish I had easily found on someone else’s blog, but had to invent or piece together myself.

Today’s nugget – launching an arbitrary .exe at low thread priority from powershell. I’m used to doing this with ‘start’ from a cmd shell, so I was frustrated at first that I didn’t see a way to do this with the “&” method of invoking an exe. Googled around and found others wanting something similar to start for PS. Then I remembered – *light bulb* – I’m in the CLR, enjoy the freedom and power 🙂

So here is my simple function that uses System.Diagnostics.Process to launch 7z.exe to compress a file at low priority.

function CopyTo7zArchive([System.IO.FileInfo] $inFile){
$archiveName = $inFile.FullName.Remove($inFile.FullName.Length – $inFile.Extension.Length) + “.7z”;

#If source and target both exist, then skip
if ((Test-Path $archiveNAme) -and (Test-path $inFIle.FullName)) {Write-Verbose(“7z archive already present, skipping file”); $true}
$success = $false;

$proc = New-Object System.Diagnostics.Process;
$proc.StartInfo.FileName = “c:\program files\7-zip\7z.exe”;
$proc.StartInfo.Arguments = (“a “”$archiveName”” “”” + $inFile.FullName + “”””);

$proc.StartInfo.UseShellExecute = $false;
$proc.StartInfo.RedirectStandardOutput = $true;
$proc.PriorityClass = [System.Diagnostics.ProcessPriorityClass]::Idle;
$procOutput = $proc.StandardOutput.ReadToEnd();
if ($procOutput -match “Everything is Ok” ) {$success = $true};

if ($success -eq $true) {
Write-Verbose (“Compressed source file ” + $inFile.FullName + ” to target of ” + $archiveName);
#return success
Write-Verbose (“ERROR: 7Z did not report success while compressing ” + $inFile.FullName + ” to target of ” + $archiveName + “. Deleting suspect archive file and dumping 7z output:”);
if ((Test-Path $archiveName)) {del $archiveName;}
Write-Verbose $procOutput;

$false; }


Note that if you don’t want to consume the output you can still easily wait for the .exe to exit by calling WaitForExit() on the Process object.