View Single Post
Old 11-28-2007   #1 (permalink)
ebgreen


 
 

Strange Ctrl-C behavior

Here is the scenario. I work in an environment where the users are locked
down in general and admins are given an alt ID that has admin rights. As a
result, I use a function (called elevate) to run powershell occasionally
using my alt ID. The definition of the function is at the bottom of this
post. I unfortunately did not document where I got it so I cannot give proper
credit to the original author. There is a good chance that the original
author reads these fora, so my apologies.

The curious behavior is this. When I run a non-elevated powershell session
then execute a command with a long run time, for example:

Gci -Recurse -Path C:\

I can easily stop it's execution with Ctrl-C. If however I run the exact
same command in a powershell session that I stared using the Elevate function
(I plan to change the function name to Verb-Noun soon btw), then Ctrl-C will
not stop the command execution. Has anyone else seen similar behavior?



Here is the definition for the Elevate function.


$ndx=0
if ($MyInvocation.PositionMessage -match 'char\d+)') {
$ndx = [int]$matchesΏ]
}

$setDirCmd = "[Environment]::CurrentDirectory = (set-location
-LiteralPath '$pwd' -PassThru).ProviderPath"

$OFS = ","
Write-Debug "`$MyInvocation.Line args index is $ndx; `$args are
<$args>"

if ($argsΎ] -is [Scriptblock]) {
$script = $argsΎ]
Write-Debug "Starting PowerShell with scriptblock: {$script}"
start-process powershell.exe -verb runas -workingdir $pwd `
-arguments "-noexit -command & {$setDirCmd; $script}"
}
elseif ($argsΎ].length -gt 0) {
$startProcessArgs = $MyInvocation.Line.Substring($ndx)

$app = get-command $argsΎ] | select -first 1 | ? {$_.CommandType -eq
'Application'}
if ($app) {
$startProcessArgs =
$startProcessArgs.Substring($argsΎ].Length).Trim()
Write-Debug "Starting <$($app.Path)> with args:
<$startProcessArgs>"
start-process $app.Path -verb runas -workingdir $pwd -arguments
$startProcessArgs
}
else {
Write-Debug "Starting PowerShell with args: <$startProcessArgs>"
start-process powershell.exe -verb runas -workingdir $pwd `
-arguments "-noexit -command & {$setDirCmd;
$startProcessArgs}"
}
}
else {
Write-Debug "Starting Powershell without args"
start-process powershell.exe -verb runas -workingdir $pwd `
-arguments "-noexit -command & {$setDirCmd}"
}

My System SpecsSystem Spec