Team Ai
Datasetpublic

MegaBites-AI/Windows-powershell

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes308downloads
ProcessCodeMethods.cs73 linesDownload Raw Back to engine
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4using System;5using System.Diagnostics;6using System.Management.Automation;7using System.Runtime.InteropServices;8 9namespace Microsoft.PowerShell10{11    /// <summary>12    /// Helper functions for process info.13    /// </summary>14    public static class ProcessCodeMethods15    {16        private const int InvalidProcessId = -1;17 18        internal static Process GetParent(this Process process)19        {20            try21            {22                var pid = GetParentPid(process);23                if (pid == InvalidProcessId)24                {25                    return null;26                }27 28                var candidate = Process.GetProcessById(pid);29 30                // if the candidate was started later than process, the pid has been recycled31                return candidate.StartTime > process.StartTime ? null : candidate;32            }33            catch (Exception)34            {35                return null;36            }37        }38 39        /// <summary>40        /// CodeMethod for getting the parent process of a process.41        /// </summary>42        /// <param name="obj"></param>43        /// <returns>The parent process, or null if the parent is no longer running.</returns>44        public static object GetParentProcess(PSObject obj)45        {46            var process = PSObject.Base(obj) as Process;47            return process?.GetParent();48        }49 50        /// <summary>51        /// Returns the parent id of a process or -1 if it fails.52        /// </summary>53        /// <param name="process"></param>54        /// <returns>The pid of the parent process.</returns>55#if UNIX56        internal static int GetParentPid(Process process)57        {58            return Platform.NonWindowsGetProcessParentPid(process.Id);59        }60#else61        internal static int GetParentPid(Process process)62        {63            Diagnostics.Assert(process != null, "Ensure process is not null before calling");64            Interop.Windows.PROCESS_BASIC_INFORMATION pbi;65            int size;66            var res = Interop.Windows.NtQueryInformationProcess(process.Handle, 0, out pbi, Marshal.SizeOf<Interop.Windows.PROCESS_BASIC_INFORMATION>(), out size);67 68            return res != 0 ? InvalidProcessId : pbi.InheritedFromUniqueProcessId.ToInt32();69        }70#endif71    }72}73