2014-09-24 62 views
0

我有一個遞歸Powershell腳本來調用自身的高架構。我想將父進程的PID作爲參數發送給子進程。現在我正在嘗試一些這樣的事情,但它不起作用。在遞歸PowerShell腳本中傳遞參數

param($someid) 

$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent() 
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID) 

# Get the security principal for the Administrator role 
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator 

# Check to see if we are currently running "as Administrator" 
if ($myWindowsPrincipal.IsInRole($adminRole)) 
{ 
    Write-Host $PID 
    "Child process" 
    #Write-Host $someid 

    # We are running "as Administrator" - so change the title and background color to indicate this 
    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)" 
    $Host.UI.RawUI.BackgroundColor = "DarkBlue" 
    Clear-Host 
} 
else 
{ 
    "Parent process" 
    Write-Host $PID 

    # We are not running "as Administrator" - so relaunch as administrator 
    # Create a new process object that starts PowerShell 
    $newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell"; 

    # Specify the current script path and name as a parameter 
    $newProcess.Arguments = $myInvocation.MyCommand.Definition; 
    #$newProcess.Arguments = $PID; 

    # Indicate that the process should be elevated 
    $newProcess.Verb = "runas"; 

    # Start the new process 
    [int]$arg = $PID 
    [System.Diagnostics.Process]::Start($newProcess); 

    # Exit from the current, unelevated, process 

    Exit 
} 

回答

0

子進程可以找到它的ParentProcessIDWMI(使用Get-WmiObject,別名gwmi):

gwmi win32_process | select ProcessID, ParentProcessID, Name | where {$_.ProcessID -eq "$pid"} | ft -AutoSize 

,我可能把它分配給一個變量重用後來在腳本中。

$PPI = (gwmi win32_process | select ProcessID, ParentProcessID, Name | where {$_.ProcessID -eq "$pid"} | Select-Object ParentProcessID).ParentProcessID 

相關文章:How do I determine if a process on Windows "has no parent"?

+0

您好,我試過分配PID到一個全局變量的第二種方式。但是它不會工作,因爲每次腳本從頭開始執行並且變量都是空的。不能通過傳遞參數來完成嗎? – nitinsh99 2014-09-24 18:21:33

+0

要在會話之間持續存在,您需要將$ pid輸出到註冊表項或文本文件,以便在第二次運行時從腳本中讀取它。 – 2014-09-25 04:55:12

+0

所以基本上你說我在這種情況下不能通過PID作爲參數? – nitinsh99 2014-09-25 13:37:43