我有一个递归的Powershell脚本,可以通过提升的rigth来调用自己。我想将父进程的PID作为参数发送到子进程。现在我正在尝试这样的事情,但它没有用。
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 :(得分:0)
子进程可以从WMI找到ParentProcessID
(使用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"?