| |
| |
|
|
| using System; |
| using System.Collections; |
| using System.Collections.Generic; |
| using System.Collections.ObjectModel; |
| using System.Collections.Specialized; |
| using System.ComponentModel; |
| using System.Diagnostics; |
| using System.Diagnostics.CodeAnalysis; |
| using System.IO; |
| using System.Management.Automation; |
| using System.Management.Automation.Internal; |
| using System.Management.Automation.Language; |
| using System.Net; |
| using System.Runtime.InteropServices; |
| using System.Runtime.Serialization; |
| using System.Security.Principal; |
| using System.Text; |
| using System.Threading; |
| using Microsoft.Management.Infrastructure; |
| using Microsoft.PowerShell.Commands.Internal; |
| using Microsoft.Win32.SafeHandles; |
|
|
| namespace Microsoft.PowerShell.Commands |
| { |
| #region ProcessBaseCommand |
| |
| |
| |
| public abstract class ProcessBaseCommand : Cmdlet |
| { |
| #region Parameters |
| |
| |
| |
| internal enum MatchMode |
| { |
| |
| |
| |
| All, |
| |
| |
| |
| ByName, |
| |
| |
| |
| ById, |
| |
| |
| |
| ByInput |
| } |
| |
| |
| |
| internal MatchMode myMode = MatchMode.All; |
|
|
| |
| |
| |
| |
| internal string[] processNames = null; |
|
|
| |
| |
| internal int[] processIds = null; |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| [Parameter( |
| ParameterSetName = "InputObject", |
| Mandatory = true, |
| ValueFromPipeline = true)] |
| public virtual Process[] InputObject |
| { |
| get |
| { |
| return _input; |
| } |
|
|
| set |
| { |
| myMode = MatchMode.ByInput; |
| _input = value; |
| } |
| } |
|
|
| private Process[] _input = null; |
| #endregion Parameters |
|
|
| #region Internal |
|
|
| |
| |
| private List<Process> _matchingProcesses = new(); |
| private readonly Dictionary<int, Process> _keys = new(); |
|
|
| |
| |
| |
| |
| |
| internal List<Process> MatchingProcesses() |
| { |
| _matchingProcesses.Clear(); |
| switch (myMode) |
| { |
| case MatchMode.ById: |
| RetrieveMatchingProcessesById(); |
| break; |
|
|
| case MatchMode.ByInput: |
| RetrieveProcessesByInput(); |
| break; |
| default: |
| |
| RetrieveMatchingProcessesByProcessName(); |
| break; |
| } |
| |
| |
| _matchingProcesses.Sort(ProcessComparison); |
| return _matchingProcesses; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| private static int ProcessComparison(Process x, Process y) |
| { |
| int diff = string.Compare( |
| SafeGetProcessName(x), |
| SafeGetProcessName(y), |
| StringComparison.OrdinalIgnoreCase); |
| if (diff != 0) |
| return diff; |
| return SafeGetProcessId(x) - SafeGetProcessId(y); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| private void RetrieveMatchingProcessesByProcessName() |
| { |
| if (processNames == null) |
| { |
| _matchingProcesses = new List<Process>(AllProcesses); |
| return; |
| } |
|
|
| foreach (string pattern in processNames) |
| { |
| WildcardPattern wildcard = |
| WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); |
| bool found = false; |
| foreach (Process process in AllProcesses) |
| { |
| if (!wildcard.IsMatch(SafeGetProcessName(process))) |
| continue; |
| found = true; |
| AddIdempotent(process); |
| } |
|
|
| if (!found && |
| !WildcardPattern.ContainsWildcardCharacters(pattern)) |
| { |
| string errorText = ProcessResources.NoProcessFoundForGivenName; |
| string errorName = nameof(ProcessResources.NoProcessFoundForGivenName); |
|
|
| if (int.TryParse(pattern, out int x) && x >= 0) |
| { |
| errorText = ProcessResources.RecommendIdTagForGivenName; |
| errorName = nameof(ProcessResources.RecommendIdTagForGivenName); |
| } |
|
|
| WriteNonTerminatingError( |
| processName: pattern, |
| processId: 0, |
| targetObject: pattern, |
| innerException: null, |
| resourceId: errorText, |
| errorId: errorName, |
| category: ErrorCategory.ObjectNotFound); |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| private void RetrieveMatchingProcessesById() |
| { |
| if (processIds == null) |
| { |
| Diagnostics.Assert(false, "null processIds"); |
| throw PSTraceSource.NewInvalidOperationException(); |
| } |
|
|
| foreach (int processId in processIds) |
| { |
| Process process; |
| try |
| { |
| process = Process.GetProcessById(processId); |
| AddIdempotent(process); |
| } |
| catch (ArgumentException) |
| { |
| WriteNonTerminatingError( |
| string.Empty, |
| processId, |
| processId, |
| null, |
| ProcessResources.NoProcessFoundForGivenId, |
| "NoProcessFoundForGivenId", |
| ErrorCategory.ObjectNotFound); |
| continue; |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| private void RetrieveProcessesByInput() |
| { |
| if (InputObject == null) |
| { |
| Diagnostics.Assert(false, "null InputObject"); |
| throw PSTraceSource.NewInvalidOperationException(); |
| } |
|
|
| foreach (Process process in InputObject) |
| { |
| SafeRefresh(process); |
| AddIdempotent(process); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| internal Process[] AllProcesses => _allProcesses ??= Process.GetProcesses(); |
|
|
| private Process[] _allProcesses; |
|
|
| |
| |
| |
| |
| |
| |
| |
| private void AddIdempotent( |
| Process process) |
| { |
| int hashCode = SafeGetProcessName(process).GetHashCode() |
| ^ SafeGetProcessId(process); |
| if (!_keys.ContainsKey(hashCode)) |
| { |
| _keys.Add(hashCode, process); |
| _matchingProcesses.Add(process); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| internal void WriteNonTerminatingError( |
| Process process, |
| Exception innerException, |
| string resourceId, string errorId, |
| ErrorCategory category) |
| { |
| WriteNonTerminatingError( |
| SafeGetProcessName(process), |
| SafeGetProcessId(process), |
| process, |
| innerException, |
| resourceId, |
| errorId, |
| category); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| internal void WriteNonTerminatingError( |
| string processName, |
| int processId, |
| object targetObject, |
| Exception innerException, |
| string resourceId, |
| string errorId, |
| ErrorCategory category) |
| { |
| string message = StringUtil.Format(resourceId, |
| processName, |
| processId, |
| (innerException == null) ? string.Empty : innerException.Message); |
| ProcessCommandException exception = |
| new(message, innerException); |
| exception.ProcessName = processName; |
|
|
| WriteError(new ErrorRecord( |
| exception, errorId, category, targetObject)); |
| } |
|
|
| |
| |
| internal static string SafeGetProcessName(Process process) |
| { |
| try |
| { |
| return process.ProcessName; |
| } |
| catch (Win32Exception) |
| { |
| return string.Empty; |
| } |
| catch (InvalidOperationException) |
| { |
| return string.Empty; |
| } |
| } |
|
|
| |
| internal static int SafeGetProcessId(Process process) |
| { |
| try |
| { |
| return process.Id; |
| } |
| catch (Win32Exception) |
| { |
| return int.MinValue; |
| } |
| catch (InvalidOperationException) |
| { |
| return int.MinValue; |
| } |
| } |
|
|
| internal static void SafeRefresh(Process process) |
| { |
| try |
| { |
| process.Refresh(); |
| } |
| catch (Win32Exception) |
| { |
| } |
| catch (InvalidOperationException) |
| { |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| internal static bool TryHasExited(Process process) |
| { |
| bool hasExited = true; |
|
|
| try |
| { |
| hasExited = process.HasExited; |
| } |
| catch (Win32Exception) |
| { |
| hasExited = false; |
| } |
| catch (InvalidOperationException) |
| { |
| hasExited = false; |
| } |
|
|
| return hasExited; |
| } |
|
|
| #endregion Internal |
| } |
| #endregion ProcessBaseCommand |
|
|
| #region GetProcessCommand |
| |
| |
| |
| [Cmdlet(VerbsCommon.Get, "Process", DefaultParameterSetName = NameParameterSet, |
| HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096814", RemotingCapability = RemotingCapability.SupportedByCommand)] |
| [OutputType(typeof(ProcessModule), typeof(FileVersionInfo), typeof(Process))] |
| public sealed class GetProcessCommand : ProcessBaseCommand |
| { |
| #region ParameterSetStrings |
|
|
| private const string NameParameterSet = "Name"; |
| private const string IdParameterSet = "Id"; |
| private const string InputObjectParameterSet = "InputObject"; |
| private const string NameWithUserNameParameterSet = "NameWithUserName"; |
| private const string IdWithUserNameParameterSet = "IdWithUserName"; |
| private const string InputObjectWithUserNameParameterSet = "InputObjectWithUserName"; |
|
|
| #endregion ParameterSetStrings |
|
|
| #region Parameters |
|
|
| |
| |
| |
| [Parameter(Position = 0, ParameterSetName = NameParameterSet, ValueFromPipelineByPropertyName = true)] |
| [Parameter(Position = 0, ParameterSetName = NameWithUserNameParameterSet, ValueFromPipelineByPropertyName = true)] |
| [Alias("ProcessName")] |
| [ValidateNotNullOrEmpty] |
| public string[] Name |
| { |
| get |
| { |
| return processNames; |
| } |
|
|
| set |
| { |
| myMode = MatchMode.ByName; |
| processNames = value; |
| } |
| } |
|
|
| |
| |
| |
| [Parameter(ParameterSetName = IdParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] |
| [Parameter(ParameterSetName = IdWithUserNameParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] |
| [Alias("PID")] |
| public int[] Id |
| { |
| get |
| { |
| return processIds; |
| } |
|
|
| set |
| { |
| myMode = MatchMode.ById; |
| processIds = value; |
| } |
| } |
|
|
| |
| |
| |
| [Parameter(ParameterSetName = InputObjectParameterSet, Mandatory = true, ValueFromPipeline = true)] |
| [Parameter(ParameterSetName = InputObjectWithUserNameParameterSet, Mandatory = true, ValueFromPipeline = true)] |
| public override Process[] InputObject |
| { |
| get |
| { |
| return base.InputObject; |
| } |
|
|
| set |
| { |
| base.InputObject = value; |
| } |
| } |
|
|
| |
| |
| |
| [Parameter(ParameterSetName = NameWithUserNameParameterSet, Mandatory = true)] |
| [Parameter(ParameterSetName = IdWithUserNameParameterSet, Mandatory = true)] |
| [Parameter(ParameterSetName = InputObjectWithUserNameParameterSet, Mandatory = true)] |
| public SwitchParameter IncludeUserName { get; set; } |
|
|
| |
| |
| |
| [Parameter(ParameterSetName = NameParameterSet)] |
| [Parameter(ParameterSetName = IdParameterSet)] |
| [Parameter(ParameterSetName = InputObjectParameterSet)] |
| [ValidateNotNull] |
| public SwitchParameter Module { get; set; } |
|
|
| |
| |
| |
| [Parameter(ParameterSetName = NameParameterSet)] |
| [Parameter(ParameterSetName = IdParameterSet)] |
| [Parameter(ParameterSetName = InputObjectParameterSet)] |
| [Alias("FV", "FVI")] |
| [ValidateNotNull] |
| public SwitchParameter FileVersionInfo { get; set; } |
|
|
| #endregion Parameters |
|
|
| #region Overrides |
|
|
| |
| |
| |
| protected override void ProcessRecord() |
| { |
| foreach (Process process in MatchingProcesses()) |
| { |
| if (Module.IsPresent && FileVersionInfo.IsPresent) |
| { |
| ProcessModule tempmodule = null; |
| try |
| { |
| ProcessModuleCollection modules = process.Modules; |
| foreach (ProcessModule pmodule in modules) |
| { |
| |
| tempmodule = pmodule; |
| WriteObject(pmodule.FileVersionInfo, true); |
| } |
| } |
| catch (InvalidOperationException exception) |
| { |
| WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModuleFileVer, "CouldNotEnumerateModuleFileVer", ErrorCategory.PermissionDenied); |
| } |
| catch (ArgumentException exception) |
| { |
| WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModuleFileVer, "CouldNotEnumerateModuleFileVer", ErrorCategory.PermissionDenied); |
| } |
| catch (Win32Exception exception) |
| { |
| try |
| { |
| if (exception.HResult == 299) |
| { |
| WriteObject(tempmodule.FileVersionInfo, true); |
| } |
| else |
| { |
| WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModuleFileVer, "CouldNotEnumerateModuleFileVer", ErrorCategory.PermissionDenied); |
| } |
| } |
| catch (Win32Exception ex) |
| { |
| WriteNonTerminatingError(process, ex, ProcessResources.CouldNotEnumerateModuleFileVer, "CouldNotEnumerateModuleFileVer", ErrorCategory.PermissionDenied); |
| } |
| } |
| catch (Exception exception) |
| { |
| WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModuleFileVer, "CouldNotEnumerateModuleFileVer", ErrorCategory.PermissionDenied); |
| } |
| } |
| else if (Module.IsPresent) |
| { |
| try |
| { |
| WriteObject(process.Modules, true); |
| } |
| catch (Win32Exception exception) |
| { |
| try |
| { |
| if (exception.HResult == 299) |
| { |
| WriteObject(process.Modules, true); |
| } |
| else |
| { |
| WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModules, "CouldNotEnumerateModules", ErrorCategory.PermissionDenied); |
| } |
| } |
| catch (Win32Exception ex) |
| { |
| WriteNonTerminatingError(process, ex, ProcessResources.CouldNotEnumerateModules, "CouldNotEnumerateModules", ErrorCategory.PermissionDenied); |
| } |
| } |
| catch (PipelineStoppedException) |
| { |
| throw; |
| } |
| catch (Exception exception) |
| { |
| WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModules, "CouldNotEnumerateModules", ErrorCategory.PermissionDenied); |
| } |
| } |
| else if (FileVersionInfo.IsPresent) |
| { |
| try |
| { |
| ProcessModule mainModule = process.MainModule; |
| if (mainModule != null) |
| { |
| WriteObject(mainModule.FileVersionInfo, true); |
| } |
| } |
| catch (InvalidOperationException exception) |
| { |
| WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateFileVer, "CouldNotEnumerateFileVer", ErrorCategory.PermissionDenied); |
| } |
| catch (ArgumentException exception) |
| { |
| WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateFileVer, "CouldNotEnumerateFileVer", ErrorCategory.PermissionDenied); |
| } |
| catch (Win32Exception exception) |
| { |
| try |
| { |
| if (exception.HResult == 299) |
| { |
| WriteObject(process.MainModule?.FileVersionInfo, true); |
| } |
| else |
| { |
| WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateFileVer, "CouldNotEnumerateFileVer", ErrorCategory.PermissionDenied); |
| } |
| } |
| catch (Win32Exception ex) |
| { |
| WriteNonTerminatingError(process, ex, ProcessResources.CouldNotEnumerateFileVer, "CouldNotEnumerateFileVer", ErrorCategory.PermissionDenied); |
| } |
| } |
| catch (Exception exception) |
| { |
| WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateFileVer, "CouldNotEnumerateFileVer", ErrorCategory.PermissionDenied); |
| } |
| } |
| else |
| { |
| WriteObject(IncludeUserName.IsPresent ? AddUserNameToProcess(process) : process); |
| } |
| } |
| } |
|
|
| #endregion Overrides |
|
|
| #region Privates |
|
|
| |
| |
| |
| private const string TypeNameForProcessWithUserName = "System.Diagnostics.Process#IncludeUserName"; |
|
|
| |
| |
| |
| |
| |
| private static PSObject AddUserNameToProcess(Process process) |
| { |
| |
| string userName = RetrieveProcessUserName(process); |
|
|
| PSObject processAsPsobj = PSObject.AsPSObject(process); |
| PSNoteProperty noteProperty = new("UserName", userName); |
|
|
| processAsPsobj.Properties.Add(noteProperty, true); |
| processAsPsobj.TypeNames.Insert(0, TypeNameForProcessWithUserName); |
|
|
| return processAsPsobj; |
| } |
|
|
| |
| |
| |
| |
| |
| private static string RetrieveProcessUserName(Process process) |
| { |
| string userName = null; |
| #if UNIX |
| userName = Platform.NonWindowsGetUserFromPid(process.Id); |
| #else |
| IntPtr tokenUserInfo = IntPtr.Zero; |
| IntPtr processTokenHandler = IntPtr.Zero; |
|
|
| const uint TOKEN_QUERY = 0x0008; |
|
|
| try |
| { |
| int error; |
| if (!Win32Native.OpenProcessToken(process.Handle, TOKEN_QUERY, out processTokenHandler)) |
| { |
| return null; |
| } |
|
|
| |
| int tokenInfoLength = 256; |
| tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength); |
| if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) |
| { |
| error = Marshal.GetLastWin32Error(); |
| if (error == Win32Native.ERROR_INSUFFICIENT_BUFFER) |
| { |
| Marshal.FreeHGlobal(tokenUserInfo); |
| tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength); |
|
|
| if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) |
| { |
| return null; |
| } |
| } |
| else |
| { |
| return null; |
| } |
| } |
|
|
| var tokenUser = Marshal.PtrToStructure<Win32Native.TOKEN_USER>(tokenUserInfo); |
| SecurityIdentifier sid = new SecurityIdentifier(tokenUser.User.Sid); |
| userName = sid.Translate(typeof(System.Security.Principal.NTAccount)).Value; |
| } |
| catch (NotSupportedException) |
| { |
| |
| } |
| catch (IdentityNotMappedException) |
| { |
| |
| } |
| catch (InvalidOperationException) |
| { |
| |
| } |
| catch (Win32Exception) |
| { |
| |
| } |
| catch (Exception) |
| { |
| |
| } |
| finally |
| { |
| if (tokenUserInfo != IntPtr.Zero) |
| { |
| Marshal.FreeHGlobal(tokenUserInfo); |
| } |
|
|
| if (processTokenHandler != IntPtr.Zero) |
| { |
| Win32Native.CloseHandle(processTokenHandler); |
| } |
| } |
| #endif |
| return userName; |
| } |
|
|
| #endregion Privates |
| } |
| #endregion GetProcessCommand |
|
|
| #region WaitProcessCommand |
| |
| |
| |
| [Cmdlet(VerbsLifecycle.Wait, "Process", DefaultParameterSetName = "Name", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097146")] |
| [OutputType(typeof(Process))] |
| public sealed class WaitProcessCommand : ProcessBaseCommand |
| { |
| #region Parameters |
|
|
| |
| |
| |
| [Parameter( |
| ParameterSetName = "Id", |
| Position = 0, |
| Mandatory = true, |
| ValueFromPipelineByPropertyName = true)] |
| [ValidateNotNullOrEmpty] |
| [Alias("PID", "ProcessId")] |
| [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] |
| public int[] Id |
| { |
| get |
| { |
| return processIds; |
| } |
|
|
| set |
| { |
| myMode = MatchMode.ById; |
| processIds = value; |
| } |
| } |
|
|
| |
| |
| |
| [Parameter( |
| ParameterSetName = "Name", |
| Position = 0, |
| Mandatory = true, |
| ValueFromPipelineByPropertyName = true)] |
| [Alias("ProcessName")] |
| [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] |
| public string[] Name |
| { |
| get |
| { |
| return processNames; |
| } |
|
|
| set |
| { |
| myMode = MatchMode.ByName; |
| processNames = value; |
| } |
| } |
|
|
| |
| |
| |
| [Parameter(Position = 1)] |
| [Alias("TimeoutSec")] |
| [ValidateNotNullOrEmpty] |
| [ValidateRange(0, 32767)] |
| public int Timeout |
| { |
| get |
| { |
| return _timeout; |
| } |
|
|
| set |
| { |
| _timeout = value; |
| _timeOutSpecified = true; |
| } |
| } |
|
|
| |
| |
| |
| [Parameter] |
| public SwitchParameter Any { get; set; } |
|
|
| |
| |
| |
| [Parameter] |
| public SwitchParameter PassThru { get; set; } |
|
|
| private int _timeout = 0; |
| private bool _timeOutSpecified; |
|
|
| #endregion Parameters |
|
|
| private bool _disposed = false; |
|
|
| #region IDisposable |
| |
| |
| |
| public void Dispose() |
| { |
| if (!_disposed) |
| { |
| if (_waitHandle != null) |
| { |
| _waitHandle.Dispose(); |
| _waitHandle = null; |
| } |
|
|
| _disposed = true; |
| } |
| } |
|
|
| #endregion |
|
|
| #region private methods |
| |
| private void myProcess_Exited(object sender, System.EventArgs e) |
| { |
| if (Any || (Interlocked.Decrement(ref _numberOfProcessesToWaitFor) == 0)) |
| { |
| _waitHandle?.Set(); |
| } |
| } |
|
|
| #endregion |
|
|
| #region Overrides |
|
|
| private readonly List<Process> _processList = new(); |
|
|
| |
| private ManualResetEvent _waitHandle; |
| private int _numberOfProcessesToWaitFor; |
|
|
| |
| |
| |
| protected override void ProcessRecord() |
| { |
| |
| foreach (Process process in MatchingProcesses()) |
| { |
| |
| if (process.Id == 0) |
| { |
| WriteNonTerminatingError(process, null, ProcessResources.WaitOnIdleProcess, "WaitOnIdleProcess", ErrorCategory.ObjectNotFound); |
| continue; |
| } |
|
|
| |
| if (process.Id.Equals(Environment.ProcessId)) |
| { |
| WriteNonTerminatingError(process, null, ProcessResources.WaitOnItself, "WaitOnItself", ErrorCategory.ObjectNotFound); |
| continue; |
| } |
|
|
| _processList.Add(process); |
| } |
| } |
|
|
| |
| |
| |
| protected override void EndProcessing() |
| { |
| _waitHandle = new ManualResetEvent(false); |
| foreach (Process process in _processList) |
| { |
| try |
| { |
| |
| if (Any && process.HasExited) |
| { |
| _waitHandle.Set(); |
| } |
| else if (!process.HasExited) |
| { |
| process.EnableRaisingEvents = true; |
| process.Exited += myProcess_Exited; |
| if (!process.HasExited) |
| { |
| System.Threading.Interlocked.Increment(ref _numberOfProcessesToWaitFor); |
| } |
| } |
| } |
| catch (Win32Exception exception) |
| { |
| WriteNonTerminatingError(process, exception, ProcessResources.ProcessIsNotTerminated, "ProcessNotTerminated", ErrorCategory.CloseError); |
| } |
| } |
|
|
| bool hasTimedOut = false; |
| if (_numberOfProcessesToWaitFor > 0) |
| { |
| if (_timeOutSpecified) |
| { |
| hasTimedOut = !_waitHandle.WaitOne(_timeout * 1000); |
| } |
| else |
| { |
| _waitHandle.WaitOne(); |
| } |
| } |
|
|
| if (hasTimedOut || (!Any && _numberOfProcessesToWaitFor > 0)) |
| { |
| foreach (Process process in _processList) |
| { |
| try |
| { |
| if (!process.HasExited) |
| { |
| string message = StringUtil.Format(ProcessResources.ProcessNotTerminated, new object[] { process.ProcessName, process.Id }); |
| ErrorRecord errorRecord = new(new TimeoutException(message), "ProcessNotTerminated", ErrorCategory.CloseError, process); |
| WriteError(errorRecord); |
| } |
| } |
| catch (Win32Exception exception) |
| { |
| WriteNonTerminatingError(process, exception, ProcessResources.ProcessIsNotTerminated, "ProcessNotTerminated", ErrorCategory.CloseError); |
| } |
| } |
| } |
|
|
| if (PassThru) |
| { |
| WriteObject(_processList, enumerateCollection: true); |
| } |
| } |
|
|
| |
| |
| |
| protected override void StopProcessing() => _waitHandle?.Set(); |
|
|
| #endregion Overrides |
|
|
| } |
| #endregion WaitProcessCommand |
|
|
| #region StopProcessCommand |
| |
| |
| |
| |
| |
| |
| |
| [Cmdlet(VerbsLifecycle.Stop, "Process", |
| DefaultParameterSetName = "Id", |
| SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097058")] |
| [OutputType(typeof(Process))] |
| public sealed class StopProcessCommand : ProcessBaseCommand |
| { |
| #region Parameters |
| |
| |
| |
| [Parameter( |
| ParameterSetName = "Name", |
| Mandatory = true, |
| ValueFromPipelineByPropertyName = true)] |
| [Alias("ProcessName")] |
| public string[] Name |
| { |
| get |
| { |
| return processNames; |
| } |
|
|
| set |
| { |
| processNames = value; |
| myMode = MatchMode.ByName; |
| } |
| } |
|
|
| |
| |
| |
| [Parameter( |
| Position = 0, |
| ParameterSetName = "Id", |
| Mandatory = true, |
| ValueFromPipelineByPropertyName = true)] |
| public int[] Id |
| { |
| get |
| { |
| return processIds; |
| } |
|
|
| set |
| { |
| myMode = MatchMode.ById; |
| processIds = value; |
| } |
| } |
|
|
| |
| |
| |
| [Parameter( |
| Position = 0, |
| ParameterSetName = "InputObject", |
| Mandatory = true, |
| ValueFromPipeline = true)] |
| [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] |
| public new Process[] InputObject |
| { |
| get |
| { |
| return base.InputObject; |
| } |
|
|
| set |
| { |
| base.InputObject = value; |
| } |
| } |
|
|
| private bool _passThru; |
| |
| |
| |
| [Parameter] |
| public SwitchParameter PassThru |
| { |
| get { return _passThru; } |
|
|
| set { _passThru = value; } |
| } |
|
|
| |
| |
| |
| |
| |
| [Parameter] |
| [ValidateNotNullOrEmpty] |
| public SwitchParameter Force { get; set; } |
|
|
| #endregion Parameters |
|
|
| #region Overrides |
| |
| |
| |
| |
| protected override void ProcessRecord() |
| { |
| if (myMode == MatchMode.All || (myMode == MatchMode.ByName && processNames == null)) |
| { |
| Diagnostics.Assert(false, "trying to kill all processes"); |
| throw PSTraceSource.NewInvalidOperationException(); |
| } |
|
|
| foreach (Process process in MatchingProcesses()) |
| { |
| |
| |
| |
| string targetString = StringUtil.Format( |
| ProcessResources.ProcessNameForConfirmation, |
| SafeGetProcessName(process), |
| SafeGetProcessId(process)); |
|
|
| if (!ShouldProcess(targetString)) |
| { |
| continue; |
| } |
|
|
| try |
| { |
| |
| |
| |
| |
| if (process.HasExited) |
| { |
| if (PassThru) |
| WriteObject(process); |
| continue; |
| } |
| } |
| catch (NotSupportedException ex) |
| { |
| WriteNonTerminatingError( |
| process, ex, ProcessResources.CouldNotStopProcess, |
| "CouldNotStopProcess", ErrorCategory.InvalidOperation); |
| continue; |
| } |
| catch (Win32Exception ex) |
| { |
| WriteNonTerminatingError( |
| process, ex, ProcessResources.CouldNotStopProcess, |
| "CouldNotStopProcess", ErrorCategory.CloseError); |
| continue; |
| } |
|
|
| try |
| { |
| if (Environment.ProcessId == SafeGetProcessId(process)) |
| { |
| _shouldKillCurrentProcess = true; |
| continue; |
| } |
|
|
| if (Platform.IsWindows && !Force) |
| { |
| if (!IsProcessOwnedByCurrentUser(process)) |
| { |
| string message = StringUtil.Format( |
| ProcessResources.ConfirmStopProcess, |
| SafeGetProcessName(process), |
| SafeGetProcessId(process)); |
|
|
| |
| if (!ShouldContinue(message, null, ref _yesToAll, ref _noToAll)) |
| continue; |
| } |
| } |
|
|
| |
| if (string.Equals(SafeGetProcessName(process), "SVCHOST", StringComparison.OrdinalIgnoreCase)) |
| { |
| StopDependentService(process); |
| } |
|
|
| if (!process.HasExited) |
| { |
| process.Kill(); |
| } |
| } |
| catch (Win32Exception exception) |
| { |
| if (!TryHasExited(process)) |
| { |
| WriteNonTerminatingError( |
| process, exception, ProcessResources.CouldNotStopProcess, |
| "CouldNotStopProcess", ErrorCategory.CloseError); |
| continue; |
| } |
| } |
| catch (InvalidOperationException exception) |
| { |
| if (!TryHasExited(process)) |
| { |
| WriteNonTerminatingError( |
| process, exception, ProcessResources.CouldNotStopProcess, |
| "CouldNotStopProcess", ErrorCategory.CloseError); |
| continue; |
| } |
| } |
|
|
| if (PassThru) |
| WriteObject(process); |
| } |
| } |
|
|
| |
| |
| |
| protected override void EndProcessing() |
| { |
| if (_shouldKillCurrentProcess) |
| { |
| StopProcess(Process.GetCurrentProcess()); |
| } |
| } |
|
|
| #endregion Overrides |
|
|
| #region Private |
| |
| |
| |
| private bool _shouldKillCurrentProcess; |
|
|
| |
| |
| |
| private bool _yesToAll, _noToAll; |
|
|
| |
| |
| |
| private string _currentUserName; |
|
|
| |
| |
| |
| |
| |
| private bool IsProcessOwnedByCurrentUser(Process process) |
| { |
| const uint TOKEN_QUERY = 0x0008; |
| IntPtr ph = IntPtr.Zero; |
| try |
| { |
| if (Win32Native.OpenProcessToken(process.Handle, TOKEN_QUERY, out ph)) |
| { |
| if (_currentUserName == null) |
| { |
| using (var currentUser = WindowsIdentity.GetCurrent()) |
| { |
| _currentUserName = currentUser.Name; |
| } |
| } |
|
|
| using (var processUser = new WindowsIdentity(ph)) |
| { |
| return string.Equals(processUser.Name, _currentUserName, StringComparison.OrdinalIgnoreCase); |
| } |
| } |
| } |
| catch (IdentityNotMappedException) |
| { |
| |
| |
| } |
| catch (ArgumentException) |
| { |
| |
| |
| } |
| finally |
| { |
| if (ph != IntPtr.Zero) |
| { |
| Win32Native.CloseHandle(ph); |
| } |
| } |
|
|
| return false; |
| } |
|
|
| |
| |
| |
| |
| private void StopDependentService(Process process) |
| { |
| string queryString = "Select * From Win32_Service Where ProcessId=" + SafeGetProcessId(process) + " And State !='Stopped'"; |
|
|
| try |
| { |
| using (CimSession cimSession = CimSession.Create(null)) |
| { |
| IEnumerable<CimInstance> serviceList = |
| cimSession.QueryInstances("root/cimv2", "WQL", queryString); |
| foreach (CimInstance oService in serviceList) |
| { |
| string serviceName = oService.CimInstanceProperties["Name"].Value.ToString(); |
| using (var service = new System.ServiceProcess.ServiceController(serviceName)) |
| { |
| try |
| { |
| service.Stop(); |
| |
| service.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 2)); |
| } |
| catch (Win32Exception) { } |
| catch (InvalidOperationException) { } |
| catch (System.ServiceProcess.TimeoutException) { } |
| } |
| } |
| } |
| } |
| catch (CimException ex) |
| { |
| var errorRecord = new ErrorRecord(ex, "GetCimException", ErrorCategory.InvalidOperation, null); |
| WriteError(errorRecord); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| private void StopProcess(Process process) |
| { |
| Exception exception = null; |
| try |
| { |
| if (!process.HasExited) |
| { |
| process.Kill(); |
| } |
| } |
| catch (Win32Exception e) |
| { |
| exception = e; |
| } |
| catch (InvalidOperationException e) |
| { |
| exception = e; |
| } |
|
|
| if (exception != null) |
| { |
| if (!TryHasExited(process)) |
| { |
| |
| |
| WriteNonTerminatingError( |
| process, exception, ProcessResources.CouldNotStopProcess, |
| "CouldNotStopProcess", ErrorCategory.CloseError); |
| } |
| } |
| } |
|
|
| #endregion Private |
| } |
| #endregion StopProcessCommand |
|
|
| #region DebugProcessCommand |
| |
| |
| |
| [Cmdlet(VerbsDiagnostic.Debug, "Process", DefaultParameterSetName = "Name", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096809")] |
| public sealed class DebugProcessCommand : ProcessBaseCommand |
| { |
| #region Parameters |
|
|
| |
| |
| |
| [Parameter( |
| ParameterSetName = "Id", |
| Position = 0, |
| Mandatory = true, |
| ValueFromPipelineByPropertyName = true)] |
| [ValidateNotNullOrEmpty] |
| [Alias("PID", "ProcessId")] |
| [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] |
| public int[] Id |
| { |
| get |
| { |
| return processIds; |
| } |
|
|
| set |
| { |
| myMode = MatchMode.ById; |
| processIds = value; |
| } |
| } |
|
|
| |
| |
| |
| [Parameter( |
| ParameterSetName = "Name", |
| Position = 0, |
| Mandatory = true, |
| ValueFromPipelineByPropertyName = true)] |
| [Alias("ProcessName")] |
| [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] |
| public string[] Name |
| { |
| get |
| { |
| return processNames; |
| } |
|
|
| set |
| { |
| myMode = MatchMode.ByName; |
| processNames = value; |
| } |
| } |
|
|
| #endregion Parameters |
|
|
| #region Overrides |
|
|
| |
| |
| |
| protected override void ProcessRecord() |
| { |
| foreach (Process process in MatchingProcesses()) |
| { |
| string targetMessage = StringUtil.Format( |
| ProcessResources.ProcessNameForConfirmation, |
| SafeGetProcessName(process), |
| SafeGetProcessId(process)); |
|
|
| if (!ShouldProcess(targetMessage)) |
| { |
| continue; |
| } |
|
|
| |
| if (process.Id == 0) |
| { |
| WriteNonTerminatingError( |
| process, null, ProcessResources.NoDebuggerFound, |
| "NoDebuggerFound", ErrorCategory.ObjectNotFound); |
| continue; |
| } |
|
|
| try |
| { |
| |
| |
| if (process.HasExited) |
| { |
| continue; |
| } |
| } |
| catch (NotSupportedException ex) |
| { |
| WriteNonTerminatingError( |
| process, ex, ProcessResources.CouldNotDebugProcess, |
| "CouldNotDebugProcess", ErrorCategory.InvalidOperation); |
| continue; |
| } |
| catch (Win32Exception ex) |
| { |
| |
| WriteNonTerminatingError( |
| process, ex, ProcessResources.CouldNotDebugProcess, |
| "CouldNotDebugProcess", ErrorCategory.CloseError); |
| continue; |
| } |
|
|
| AttachDebuggerToProcess(process); |
| } |
| } |
|
|
| #endregion Overrides |
|
|
| |
| |
| |
| private void AttachDebuggerToProcess(Process process) |
| { |
| string searchQuery = "Select * From Win32_Process Where ProcessId=" + SafeGetProcessId(process); |
| using (CimSession cimSession = CimSession.Create(null)) |
| { |
| IEnumerable<CimInstance> processCollection = |
| cimSession.QueryInstances("root/cimv2", "WQL", searchQuery); |
| foreach (CimInstance processInstance in processCollection) |
| { |
| try |
| { |
| |
| CimMethodResult result = cimSession.InvokeMethod(processInstance, "AttachDebugger", null); |
| int returnCode = Convert.ToInt32(result.ReturnValue.Value, System.Globalization.CultureInfo.CurrentCulture); |
| if (returnCode != 0) |
| { |
| var ex = new InvalidOperationException(MapReturnCodeToErrorMessage(returnCode)); |
| WriteNonTerminatingError( |
| process, ex, ProcessResources.CouldNotDebugProcess, |
| "CouldNotDebugProcess", ErrorCategory.InvalidOperation); |
| } |
| } |
| catch (CimException e) |
| { |
| string message = e.Message?.Trim(); |
|
|
| var errorRecord = new ErrorRecord( |
| new InvalidOperationException(StringUtil.Format(ProcessResources.DebuggerError, message)), |
| "GetCimException", ErrorCategory.InvalidOperation, null); |
| WriteError(errorRecord); |
| } |
| } |
| } |
| } |
|
|
| |
| |
| |
| private static string MapReturnCodeToErrorMessage(int returnCode) |
| { |
| string errorMessage = returnCode switch |
| { |
| 2 => ProcessResources.AttachDebuggerReturnCode2, |
| 3 => ProcessResources.AttachDebuggerReturnCode3, |
| 8 => ProcessResources.AttachDebuggerReturnCode8, |
| 9 => ProcessResources.AttachDebuggerReturnCode9, |
| 21 => ProcessResources.AttachDebuggerReturnCode21, |
| _ => string.Empty |
| }; |
|
|
| Diagnostics.Assert(!string.IsNullOrEmpty(errorMessage), "Error message should not be null or empty."); |
|
|
| return errorMessage; |
| } |
| } |
| #endregion DebugProcessCommand |
|
|
| #region StartProcessCommand |
|
|
| |
| |
| |
| [Cmdlet(VerbsLifecycle.Start, "Process", DefaultParameterSetName = "Default", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097141")] |
| [OutputType(typeof(Process))] |
| public sealed class StartProcessCommand : PSCmdlet, IDisposable |
| { |
| private readonly CancellationTokenSource _cancellationTokenSource = new(); |
| private bool _isDefaultSetParameterSpecified = false; |
|
|
| #region Parameters |
|
|
| |
| |
| |
| [Parameter(Mandatory = true, Position = 0)] |
| [ValidateNotNullOrEmpty] |
| [Alias("PSPath", "Path")] |
| public string FilePath { get; set; } |
|
|
| |
| |
| |
| [Parameter(Position = 1)] |
| [Alias("Args")] |
| [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] |
| public string[] ArgumentList { get; set; } |
|
|
| |
| |
| |
| [Parameter(ParameterSetName = "Default")] |
| [Alias("RunAs")] |
| [ValidateNotNullOrEmpty] |
| [Credential] |
| public PSCredential Credential |
| { |
| get |
| { |
| return _credential; |
| } |
|
|
| set |
| { |
| _credential = value; |
| _isDefaultSetParameterSpecified = true; |
| } |
| } |
|
|
| private PSCredential _credential; |
|
|
| |
| |
| |
| [Parameter] |
| [ValidateNotNullOrEmpty] |
| public string WorkingDirectory { get; set; } |
|
|
| |
| |
| |
| [Parameter(ParameterSetName = "Default")] |
| [Alias("Lup")] |
| public SwitchParameter LoadUserProfile |
| { |
| get |
| { |
| return _loaduserprofile; |
| } |
|
|
| set |
| { |
| _loaduserprofile = value; |
| _isDefaultSetParameterSpecified = true; |
| } |
| } |
|
|
| private SwitchParameter _loaduserprofile = SwitchParameter.Present; |
|
|
| |
| |
| |
| [Parameter(ParameterSetName = "Default")] |
| [Alias("nnw")] |
| public SwitchParameter NoNewWindow |
| { |
| get |
| { |
| return _nonewwindow; |
| } |
|
|
| set |
| { |
| _nonewwindow = value; |
| _isDefaultSetParameterSpecified = true; |
| } |
| } |
|
|
| private SwitchParameter _nonewwindow; |
|
|
| |
| |
| |
| [Parameter] |
| public SwitchParameter PassThru { get; set; } |
|
|
| |
| |
| |
| [Parameter(ParameterSetName = "Default")] |
| [Alias("RSE")] |
| [ValidateNotNullOrEmpty] |
| public string RedirectStandardError |
| { |
| get |
| { |
| return _redirectstandarderror; |
| } |
|
|
| set |
| { |
| _redirectstandarderror = value; |
| _isDefaultSetParameterSpecified = true; |
| } |
| } |
|
|
| private string _redirectstandarderror; |
|
|
| |
| |
| |
| [Parameter(ParameterSetName = "Default")] |
| [Alias("RSI")] |
| [ValidateNotNullOrEmpty] |
| public string RedirectStandardInput |
| { |
| get |
| { |
| return _redirectstandardinput; |
| } |
|
|
| set |
| { |
| _redirectstandardinput = value; |
| _isDefaultSetParameterSpecified = true; |
| } |
| } |
|
|
| private string _redirectstandardinput; |
|
|
| |
| |
| |
| [Parameter(ParameterSetName = "Default")] |
| [Alias("RSO")] |
| [ValidateNotNullOrEmpty] |
| public string RedirectStandardOutput |
| { |
| get |
| { |
| return _redirectstandardoutput; |
| } |
|
|
| set |
| { |
| _redirectstandardoutput = value; |
| _isDefaultSetParameterSpecified = true; |
| } |
| } |
|
|
| private string _redirectstandardoutput; |
|
|
| |
| |
| |
| |
| |
| |
| [Parameter(ParameterSetName = "UseShellExecute")] |
| [ValidateNotNullOrEmpty] |
| [ArgumentCompleter(typeof(VerbArgumentCompleter))] |
| public string Verb { get; set; } |
|
|
| |
| |
| |
| [Parameter] |
| [ValidateNotNullOrEmpty] |
| public ProcessWindowStyle WindowStyle |
| { |
| get |
| { |
| return _windowstyle; |
| } |
|
|
| set |
| { |
| _windowstyle = value; |
| _windowstyleSpecified = true; |
| } |
| } |
|
|
| private ProcessWindowStyle _windowstyle = ProcessWindowStyle.Normal; |
| private bool _windowstyleSpecified = false; |
|
|
| |
| |
| |
| [Parameter] |
| public SwitchParameter Wait { get; set; } |
|
|
| |
| |
| |
| [Parameter(ParameterSetName = "Default")] |
| public SwitchParameter UseNewEnvironment |
| { |
| get |
| { |
| return _UseNewEnvironment; |
| } |
|
|
| set |
| { |
| _UseNewEnvironment = value; |
| _isDefaultSetParameterSpecified = true; |
| } |
| } |
|
|
| private SwitchParameter _UseNewEnvironment; |
|
|
| |
| |
| |
| [Parameter] |
| public Hashtable Environment |
| { |
| get |
| { |
| return _environment; |
| } |
|
|
| set |
| { |
| _environment = value; |
| _isDefaultSetParameterSpecified = true; |
| } |
| } |
|
|
| private Hashtable _environment; |
|
|
| #endregion |
|
|
| #region overrides |
|
|
| |
| |
| |
| protected override void BeginProcessing() |
| { |
| string message = string.Empty; |
|
|
| |
| if (Platform.IsWindowsDesktop) |
| { |
| |
| if (_nonewwindow && _windowstyleSpecified) |
| { |
| message = StringUtil.Format(ProcessResources.ContradictParametersSpecified, "-NoNewWindow", "-WindowStyle"); |
| ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); |
| WriteError(er); |
| return; |
| } |
| } |
| else |
| { |
| if (this.ParameterSetName.Equals("UseShellExecute")) |
| { |
| message = StringUtil.Format(ProcessResources.ParameterNotSupportedOnPSEdition, "-Verb", "Start-Process"); |
| } |
| else if (_windowstyleSpecified) |
| { |
| message = StringUtil.Format(ProcessResources.ParameterNotSupportedOnPSEdition, "-WindowStyle", "Start-Process"); |
| } |
|
|
| if (!string.IsNullOrEmpty(message)) |
| { |
| ErrorRecord er = new(new NotSupportedException(message), "NotSupportedException", ErrorCategory.NotImplemented, null); |
| ThrowTerminatingError(er); |
| } |
| } |
|
|
| ProcessStartInfo startInfo = new(); |
| |
| startInfo.UseShellExecute = Platform.IsWindowsDesktop; |
|
|
| |
| try |
| { |
| CommandInfo cmdinfo = CommandDiscovery.LookupCommandInfo( |
| FilePath, CommandTypes.Application | CommandTypes.ExternalScript, |
| SearchResolutionOptions.None, CommandOrigin.Internal, this.Context); |
|
|
| startInfo.FileName = cmdinfo.Definition; |
| } |
| catch (CommandNotFoundException) |
| { |
| |
| startInfo.FileName = FilePath; |
| #if UNIX |
| |
| |
|
|
| |
| |
| startInfo.UseShellExecute = (ArgumentList == null); |
| #endif |
| } |
|
|
| if (ArgumentList != null) |
| { |
| startInfo.Arguments = string.Join(' ', ArgumentList); |
| } |
|
|
| if (WorkingDirectory != null) |
| { |
| |
| WorkingDirectory = ResolveFilePath(WorkingDirectory); |
| if (!Directory.Exists(WorkingDirectory)) |
| { |
| message = StringUtil.Format(ProcessResources.InvalidInput, "WorkingDirectory"); |
| ErrorRecord er = new(new DirectoryNotFoundException(message), "DirectoryNotFoundException", ErrorCategory.InvalidOperation, null); |
| WriteError(er); |
| return; |
| } |
|
|
| startInfo.WorkingDirectory = WorkingDirectory; |
| } |
| else |
| { |
| |
| var currentDirectory = PathUtils.ResolveFilePath(this.SessionState.Path.CurrentFileSystemLocation.Path, this, isLiteralPath: true); |
| if (Directory.Exists(currentDirectory)) |
| { |
| startInfo.WorkingDirectory = currentDirectory; |
| } |
| } |
|
|
| if (this.ParameterSetName.Equals("Default")) |
| { |
| if (_isDefaultSetParameterSpecified) |
| { |
| startInfo.UseShellExecute = false; |
| } |
|
|
| if (_UseNewEnvironment) |
| { |
| startInfo.EnvironmentVariables.Clear(); |
| LoadEnvironmentVariable(startInfo, System.Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine)); |
| LoadEnvironmentVariable(startInfo, System.Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User)); |
| } |
|
|
| if (_environment != null) |
| { |
| LoadEnvironmentVariable(startInfo, _environment); |
| } |
|
|
| startInfo.WindowStyle = _windowstyle; |
|
|
| |
| |
| if (_nonewwindow && _credential is null) |
| { |
| startInfo.CreateNoWindow = _nonewwindow; |
| } |
| #if !UNIX |
| startInfo.LoadUserProfile = _loaduserprofile; |
| #endif |
| if (_credential != null) |
| { |
| NetworkCredential nwcredential = _credential.GetNetworkCredential(); |
| startInfo.UserName = nwcredential.UserName; |
| if (string.IsNullOrEmpty(nwcredential.Domain)) |
| { |
| startInfo.Domain = "."; |
| } |
| else |
| { |
| startInfo.Domain = nwcredential.Domain; |
| } |
|
|
| startInfo.Password = _credential.Password; |
| } |
|
|
| |
| if (_redirectstandardinput != null) |
| { |
| _redirectstandardinput = ResolveFilePath(_redirectstandardinput); |
| if (!File.Exists(_redirectstandardinput)) |
| { |
| message = StringUtil.Format(ProcessResources.InvalidInput, "RedirectStandardInput '" + this.RedirectStandardInput + "'"); |
| ErrorRecord er = new(new FileNotFoundException(message), "FileNotFoundException", ErrorCategory.InvalidOperation, null); |
| WriteError(er); |
| return; |
| } |
| } |
|
|
| |
| if (_redirectstandardinput != null && _redirectstandardoutput != null) |
| { |
| _redirectstandardinput = ResolveFilePath(_redirectstandardinput); |
| _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); |
| if (_redirectstandardinput.Equals(_redirectstandardoutput, StringComparison.OrdinalIgnoreCase)) |
| { |
| message = StringUtil.Format(ProcessResources.DuplicateEntry, "RedirectStandardInput", "RedirectStandardOutput"); |
| ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); |
| WriteError(er); |
| return; |
| } |
| } |
|
|
| |
| if (_redirectstandardinput != null && _redirectstandarderror != null) |
| { |
| _redirectstandardinput = ResolveFilePath(_redirectstandardinput); |
| _redirectstandarderror = ResolveFilePath(_redirectstandarderror); |
| if (_redirectstandardinput.Equals(_redirectstandarderror, StringComparison.OrdinalIgnoreCase)) |
| { |
| message = StringUtil.Format(ProcessResources.DuplicateEntry, "RedirectStandardInput", "RedirectStandardError"); |
| ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); |
| WriteError(er); |
| return; |
| } |
| } |
|
|
| |
| if (_redirectstandardoutput != null && _redirectstandarderror != null) |
| { |
| _redirectstandarderror = ResolveFilePath(_redirectstandarderror); |
| _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); |
| if (_redirectstandardoutput.Equals(_redirectstandarderror, StringComparison.OrdinalIgnoreCase)) |
| { |
| message = StringUtil.Format(ProcessResources.DuplicateEntry, "RedirectStandardOutput", "RedirectStandardError"); |
| ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); |
| WriteError(er); |
| return; |
| } |
| } |
| } |
| else if (ParameterSetName.Equals("UseShellExecute")) |
| { |
| if (Verb != null) |
| { |
| startInfo.Verb = Verb; |
| } |
|
|
| startInfo.WindowStyle = _windowstyle; |
| } |
|
|
| string targetMessage = StringUtil.Format(ProcessResources.StartProcessTarget, startInfo.FileName, startInfo.Arguments.Trim()); |
| if (!ShouldProcess(targetMessage)) |
| { |
| return; |
| } |
|
|
| Process process = null; |
|
|
| #if !UNIX |
| using JobProcessCollection jobObject = new(); |
| bool? jobAssigned = null; |
| #endif |
| if (startInfo.UseShellExecute) |
| { |
| process = StartWithShellExecute(startInfo); |
| } |
| else |
| { |
| #if UNIX |
| process = new Process() { StartInfo = startInfo }; |
| SetupInputOutputRedirection(process); |
| process.Start(); |
| if (process.StartInfo.RedirectStandardOutput) |
| { |
| process.BeginOutputReadLine(); |
| } |
|
|
| if (process.StartInfo.RedirectStandardError) |
| { |
| process.BeginErrorReadLine(); |
| } |
|
|
| if (process.StartInfo.RedirectStandardInput) |
| { |
| WriteToStandardInput(process); |
| } |
| #else |
| using ProcessInformation processInfo = StartWithCreateProcess(startInfo); |
| process = Process.GetProcessById(processInfo.ProcessId); |
|
|
| |
| |
| |
| |
| |
| if (Wait) |
| { |
| jobAssigned = jobObject.AssignProcessToJobObject(processInfo.Process); |
| } |
|
|
| |
| |
| |
| |
| |
| try |
| { |
| _ = process.Handle; |
| } |
| catch (Win32Exception e) |
| { |
| |
| |
| |
| if (PassThru) |
| { |
| string msg = StringUtil.Format(ProcessResources.FailedToCreateProcessObject, e.Message); |
| WriteDebug(msg); |
| } |
| } |
|
|
| |
| processInfo.Resume(); |
| #endif |
| } |
|
|
| if (PassThru.IsPresent) |
| { |
| if (process != null) |
| { |
| WriteObject(process); |
| } |
| else |
| { |
| message = StringUtil.Format(ProcessResources.CannotStarttheProcess); |
| ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); |
| ThrowTerminatingError(er); |
| } |
| } |
|
|
| if (Wait.IsPresent) |
| { |
| if (process != null) |
| { |
| if (!process.HasExited) |
| { |
| #if UNIX |
| process.WaitForExitAsync(_cancellationTokenSource.Token).GetAwaiter().GetResult(); |
| #else |
| |
| |
| if (jobAssigned == true || (jobAssigned is null && jobObject.AssignProcessToJobObject(process.SafeHandle))) |
| { |
| |
| jobObject.WaitForExit(_cancellationTokenSource.Token); |
| } |
| else |
| { |
| |
| |
| process.WaitForExitAsync(_cancellationTokenSource.Token).GetAwaiter().GetResult(); |
| } |
| #endif |
| } |
| } |
| else |
| { |
| message = StringUtil.Format(ProcessResources.CannotStarttheProcess); |
| ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); |
| ThrowTerminatingError(er); |
| } |
| } |
| } |
| |
| |
| |
| protected override void StopProcessing() => _cancellationTokenSource.Cancel(); |
|
|
| #endregion |
|
|
| #region IDisposable Overrides |
|
|
| |
| |
| |
| |
| |
| |
| public void Dispose() |
| { |
| _cancellationTokenSource.Dispose(); |
| } |
|
|
| #endregion |
|
|
| #region Private Methods |
|
|
| private string ResolveFilePath(string path) |
| { |
| string filepath = PathUtils.ResolveFilePath(path, this); |
| return filepath; |
| } |
|
|
| private static void LoadEnvironmentVariable(ProcessStartInfo startinfo, IDictionary EnvironmentVariables) |
| { |
| var processEnvironment = startinfo.EnvironmentVariables; |
| foreach (DictionaryEntry entry in EnvironmentVariables) |
| { |
| if (processEnvironment.ContainsKey(entry.Key.ToString())) |
| { |
| processEnvironment.Remove(entry.Key.ToString()); |
| } |
|
|
| if (entry.Value != null) |
| { |
| if (entry.Key.ToString().Equals("PATH")) |
| { |
| #if UNIX |
| processEnvironment.Add(entry.Key.ToString(), entry.Value.ToString()); |
| #else |
| processEnvironment.Add(entry.Key.ToString(), entry.Value.ToString() + Path.PathSeparator + System.Environment.GetEnvironmentVariable(entry.Key.ToString(), EnvironmentVariableTarget.Machine) + Path.PathSeparator + System.Environment.GetEnvironmentVariable(entry.Key.ToString(), EnvironmentVariableTarget.User)); |
| #endif |
| } |
| else |
| { |
| processEnvironment.Add(entry.Key.ToString(), entry.Value.ToString()); |
| } |
| } |
| } |
| } |
|
|
| #if UNIX |
| private StreamWriter _outputWriter; |
| private StreamWriter _errorWriter; |
|
|
| private void StdOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) |
| { |
| if (!string.IsNullOrEmpty(outLine.Data)) |
| { |
| _outputWriter.WriteLine(outLine.Data); |
| _outputWriter.Flush(); |
| } |
| } |
|
|
| private void StdErrorHandler(object sendingProcess, DataReceivedEventArgs outLine) |
| { |
| if (!string.IsNullOrEmpty(outLine.Data)) |
| { |
| _errorWriter.WriteLine(outLine.Data); |
| _errorWriter.Flush(); |
| } |
| } |
|
|
| private void ExitHandler(object sendingProcess, System.EventArgs e) |
| { |
| |
| |
|
|
| Thread delayedStreamClosing = new Thread(StreamClosing); |
| delayedStreamClosing.Start(); |
| } |
|
|
| private void StreamClosing() |
| { |
| Thread.Sleep(1000); |
|
|
| _outputWriter?.Dispose(); |
| _errorWriter?.Dispose(); |
| } |
|
|
| private void SetupInputOutputRedirection(Process p) |
| { |
| if (_redirectstandardinput != null) |
| { |
| p.StartInfo.RedirectStandardInput = true; |
| _redirectstandardinput = ResolveFilePath(_redirectstandardinput); |
| } |
| else |
| { |
| p.StartInfo.RedirectStandardInput = false; |
| } |
|
|
| if (_redirectstandardoutput != null) |
| { |
| p.StartInfo.RedirectStandardOutput = true; |
| _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); |
| p.OutputDataReceived += new DataReceivedEventHandler(StdOutputHandler); |
|
|
| |
| _outputWriter = new StreamWriter(new FileStream(_redirectstandardoutput, FileMode.Create)); |
| } |
| else |
| { |
| p.StartInfo.RedirectStandardOutput = false; |
| _outputWriter = null; |
| } |
|
|
| if (_redirectstandarderror != null) |
| { |
| p.StartInfo.RedirectStandardError = true; |
| _redirectstandarderror = ResolveFilePath(_redirectstandarderror); |
| p.ErrorDataReceived += new DataReceivedEventHandler(StdErrorHandler); |
|
|
| |
| _errorWriter = new StreamWriter(new FileStream(_redirectstandarderror, FileMode.Create)); |
| } |
| else |
| { |
| p.StartInfo.RedirectStandardError = false; |
| _errorWriter = null; |
| } |
|
|
| p.EnableRaisingEvents = true; |
| p.Exited += new EventHandler(ExitHandler); |
| } |
|
|
| private void WriteToStandardInput(Process p) |
| { |
| StreamWriter writer = p.StandardInput; |
| using (StreamReader reader = new StreamReader(new FileStream(_redirectstandardinput, FileMode.Open))) |
| { |
| string line = reader.ReadToEnd(); |
| writer.WriteLine(line); |
| } |
|
|
| writer.Dispose(); |
| } |
| #else |
|
|
| private SafeFileHandle GetSafeFileHandleForRedirection(string RedirectionPath, FileMode mode) |
| { |
| SafeFileHandle sf = null; |
| try |
| { |
| sf = File.OpenHandle(RedirectionPath, mode, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Inheritable, FileOptions.WriteThrough); |
| } |
| catch (Win32Exception win32ex) |
| { |
| sf?.Dispose(); |
| string message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); |
| ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); |
| ThrowTerminatingError(er); |
| } |
|
|
| return sf; |
| } |
|
|
| private static StringBuilder BuildCommandLine(string executableFileName, string arguments) |
| { |
| StringBuilder builder = new(); |
| string str = executableFileName.Trim(); |
| bool flag = str.StartsWith('"') && str.EndsWith('"'); |
| if (!flag) |
| { |
| builder.Append('"'); |
| } |
|
|
| builder.Append(str); |
| if (!flag) |
| { |
| builder.Append('"'); |
| } |
|
|
| if (!string.IsNullOrEmpty(arguments)) |
| { |
| builder.Append(' '); |
| builder.Append(arguments); |
| } |
|
|
| return builder; |
| } |
|
|
| private static byte[] ConvertEnvVarsToByteArray(StringDictionary sd) |
| { |
| string[] array = new string[sd.Count]; |
| byte[] bytes = null; |
| sd.Keys.CopyTo(array, 0); |
| string[] strArray2 = new string[sd.Count]; |
| sd.Values.CopyTo(strArray2, 0); |
| Array.Sort(array, strArray2, StringComparer.OrdinalIgnoreCase); |
| StringBuilder builder = new(); |
| for (int i = 0; i < sd.Count; i++) |
| { |
| builder.Append(array[i]); |
| builder.Append('='); |
| builder.Append(strArray2[i]); |
| builder.Append('\0'); |
| } |
|
|
| builder.Append('\0'); |
|
|
| |
| bytes = Encoding.Unicode.GetBytes(builder.ToString()); |
|
|
| return bytes; |
| } |
|
|
| private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods.STARTUPINFO lpStartupInfo, ref int creationFlags) |
| { |
| |
| |
| |
| |
| |
| |
| |
| |
| bool hasRedirection = startinfo.CreateNoWindow |
| || _redirectstandardinput is not null |
| || _redirectstandardoutput is not null |
| || _redirectstandarderror is not null; |
|
|
| |
| if (_redirectstandardinput != null) |
| { |
| startinfo.RedirectStandardInput = true; |
| _redirectstandardinput = ResolveFilePath(_redirectstandardinput); |
| lpStartupInfo.hStdInput = GetSafeFileHandleForRedirection(_redirectstandardinput, FileMode.Open); |
| } |
| else if (startinfo.CreateNoWindow) |
| { |
| lpStartupInfo.hStdInput = new SafeFileHandle( |
| ProcessNativeMethods.GetStdHandle(-10), |
| ownsHandle: false); |
| } |
|
|
| |
| if (_redirectstandardoutput != null) |
| { |
| startinfo.RedirectStandardOutput = true; |
| _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); |
| lpStartupInfo.hStdOutput = GetSafeFileHandleForRedirection(_redirectstandardoutput, FileMode.Create); |
| } |
| else if (startinfo.CreateNoWindow) |
| { |
| lpStartupInfo.hStdOutput = new SafeFileHandle( |
| ProcessNativeMethods.GetStdHandle(-11), |
| ownsHandle: false); |
| } |
|
|
| |
| if (_redirectstandarderror != null) |
| { |
| startinfo.RedirectStandardError = true; |
| _redirectstandarderror = ResolveFilePath(_redirectstandarderror); |
| lpStartupInfo.hStdError = GetSafeFileHandleForRedirection(_redirectstandarderror, FileMode.Create); |
| } |
| else if (startinfo.CreateNoWindow) |
| { |
| lpStartupInfo.hStdError = new SafeFileHandle( |
| ProcessNativeMethods.GetStdHandle(-12), |
| ownsHandle: false); |
| } |
|
|
| if (hasRedirection) |
| { |
| |
| lpStartupInfo.dwFlags = 0x100; |
| } |
|
|
| if (startinfo.CreateNoWindow) |
| { |
| |
| creationFlags = 0x00000000; |
| } |
| else |
| { |
| |
| creationFlags |= 0x00000010; |
|
|
| |
| lpStartupInfo.dwFlags |= 0x00000001; |
|
|
| |
| switch (startinfo.WindowStyle) |
| { |
| case ProcessWindowStyle.Normal: |
| |
| lpStartupInfo.wShowWindow = 1; |
| break; |
| case ProcessWindowStyle.Minimized: |
| |
| lpStartupInfo.wShowWindow = 2; |
| break; |
| case ProcessWindowStyle.Maximized: |
| |
| lpStartupInfo.wShowWindow = 3; |
| break; |
| case ProcessWindowStyle.Hidden: |
| |
| lpStartupInfo.wShowWindow = 0; |
| break; |
| } |
| } |
|
|
| |
| creationFlags |= 0x00000004; |
| } |
|
|
| |
| |
| |
| private ProcessInformation StartWithCreateProcess(ProcessStartInfo startinfo) |
| { |
| ProcessNativeMethods.STARTUPINFO lpStartupInfo = new(); |
| ProcessNativeMethods.PROCESS_INFORMATION lpProcessInformation = new(); |
| int error = 0; |
| GCHandle pinnedEnvironmentBlock = new(); |
| IntPtr AddressOfEnvironmentBlock = IntPtr.Zero; |
| string message = string.Empty; |
|
|
| |
| StringBuilder cmdLine = BuildCommandLine(startinfo.FileName, startinfo.Arguments); |
|
|
| try |
| { |
| int creationFlags = 0; |
|
|
| SetStartupInfo(startinfo, ref lpStartupInfo, ref creationFlags); |
|
|
| |
| |
| |
| |
| if (!UseNewEnvironment) |
| { |
| var environmentVars = startinfo.EnvironmentVariables; |
| if (environmentVars != null) |
| { |
| |
| creationFlags |= 0x400; |
|
|
| pinnedEnvironmentBlock = GCHandle.Alloc(ConvertEnvVarsToByteArray(environmentVars), GCHandleType.Pinned); |
| AddressOfEnvironmentBlock = pinnedEnvironmentBlock.AddrOfPinnedObject(); |
| } |
| } |
|
|
| bool flag; |
|
|
| if (_credential != null) |
| { |
| |
| ProcessNativeMethods.LogonFlags logonFlags = 0; |
| if (startinfo.LoadUserProfile) |
| { |
| logonFlags = ProcessNativeMethods.LogonFlags.LOGON_WITH_PROFILE; |
| } |
|
|
| IntPtr password = IntPtr.Zero; |
| try |
| { |
| password = (startinfo.Password == null) ? Marshal.StringToCoTaskMemUni(string.Empty) : Marshal.SecureStringToCoTaskMemUnicode(startinfo.Password); |
| flag = ProcessNativeMethods.CreateProcessWithLogonW(startinfo.UserName, startinfo.Domain, password, logonFlags, null, cmdLine, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, ref lpProcessInformation); |
| if (!flag) |
| { |
| error = Marshal.GetLastWin32Error(); |
| ErrorRecord er = null; |
|
|
| if (error == 0xc1) |
| { |
| message = StringUtil.Format(ProcessResources.InvalidApplication, FilePath); |
| } |
| else if (error == 0x424) |
| { |
| |
| |
| message = StringUtil.Format(ProcessResources.ParameterNotSupported, "-Credential", "Start-Process"); |
| er = new ErrorRecord(new NotSupportedException(message), "NotSupportedException", ErrorCategory.NotInstalled, null); |
| } |
| else |
| { |
| Win32Exception win32ex = new(error); |
| message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); |
| } |
|
|
| er ??= new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); |
| ThrowTerminatingError(er); |
| } |
|
|
| goto Label_03AE; |
| } |
| finally |
| { |
| if (password != IntPtr.Zero) |
| { |
| Marshal.ZeroFreeCoTaskMemUnicode(password); |
| } |
| } |
| } |
|
|
| |
| if (UseNewEnvironment) |
| { |
| |
| creationFlags |= 0x400; |
|
|
| IntPtr token = WindowsIdentity.GetCurrent().Token; |
| if (!ProcessNativeMethods.CreateEnvironmentBlock(out AddressOfEnvironmentBlock, token, false)) |
| { |
| Win32Exception win32ex = new(error); |
| message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); |
| var errorRecord = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); |
| ThrowTerminatingError(errorRecord); |
| } |
| } |
|
|
| ProcessNativeMethods.SECURITY_ATTRIBUTES lpProcessAttributes = new(); |
| ProcessNativeMethods.SECURITY_ATTRIBUTES lpThreadAttributes = new(); |
| flag = ProcessNativeMethods.CreateProcess(null, cmdLine, lpProcessAttributes, lpThreadAttributes, true, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, ref lpProcessInformation); |
| if (!flag) |
| { |
| error = Marshal.GetLastWin32Error(); |
|
|
| Win32Exception win32ex = new(error); |
| message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); |
| ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); |
| ThrowTerminatingError(er); |
| } |
|
|
| Label_03AE: |
|
|
| return new ProcessInformation(lpProcessInformation); |
| } |
| finally |
| { |
| if (pinnedEnvironmentBlock.IsAllocated) |
| { |
| pinnedEnvironmentBlock.Free(); |
| } |
| else |
| { |
| ProcessNativeMethods.DestroyEnvironmentBlock(AddressOfEnvironmentBlock); |
| } |
|
|
| lpStartupInfo.Dispose(); |
| } |
| } |
| #endif |
|
|
| |
| |
| |
| private Process StartWithShellExecute(ProcessStartInfo startInfo) |
| { |
| Process result = null; |
| try |
| { |
| result = Process.Start(startInfo); |
| } |
| catch (Win32Exception ex) |
| { |
| string message = StringUtil.Format(ProcessResources.InvalidStartProcess, ex.Message); |
| ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); |
| ThrowTerminatingError(er); |
| } |
|
|
| return result; |
| } |
| #endregion |
| } |
|
|
| |
| |
| |
| public class VerbArgumentCompleter : IArgumentCompleter |
| { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| public IEnumerable<CompletionResult> CompleteArgument( |
| string commandName, |
| string parameterName, |
| string wordToComplete, |
| CommandAst commandAst, |
| IDictionary fakeBoundParameters) |
| { |
| |
| if (!Platform.IsWindowsDesktop) |
| { |
| return Array.Empty<CompletionResult>(); |
| } |
|
|
| |
| if (commandName.Equals("Start-Process", StringComparison.OrdinalIgnoreCase) |
| && fakeBoundParameters.Contains("FilePath")) |
| { |
| string filePath = fakeBoundParameters["FilePath"].ToString(); |
|
|
| |
| if (Path.HasExtension(filePath)) |
| { |
| return CompleteFileVerbs(wordToComplete, filePath); |
| } |
|
|
| |
| |
| using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); |
|
|
| var commandInfo = new CmdletInfo("Get-Command", typeof(GetCommandCommand)); |
|
|
| ps.AddCommand(commandInfo); |
| ps.AddParameter("Name", filePath); |
| ps.AddParameter("CommandType", CommandTypes.Application); |
|
|
| Collection<CommandInfo> commands = ps.Invoke<CommandInfo>(); |
|
|
| |
| if (commands.Count >= 1) |
| { |
| return CompleteFileVerbs(wordToComplete, filePath: commands[0].Source); |
| } |
| } |
|
|
| return Array.Empty<CompletionResult>(); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| private static IEnumerable<CompletionResult> CompleteFileVerbs(string wordToComplete, string filePath) |
| => CompletionHelpers.GetMatchingResults( |
| wordToComplete, |
| possibleCompletionValues: new ProcessStartInfo(filePath).Verbs); |
| } |
|
|
| #if !UNIX |
| |
| |
| |
| |
| |
| internal sealed class ProcessInformation : IDisposable |
| { |
| public SafeProcessHandle Process { get; } |
|
|
| public SafeProcessHandle Thread { get; } |
|
|
| public Int32 ProcessId { get; } |
|
|
| public Int32 ThreadId { get; } |
|
|
| internal ProcessInformation(ProcessNativeMethods.PROCESS_INFORMATION info) |
| { |
| Process = new(info.hProcess, true); |
| Thread = new(info.hThread, true); |
| ProcessId = info.dwProcessId; |
| ThreadId = info.dwThreadId; |
| } |
|
|
| public void Resume() |
| { |
| ProcessNativeMethods.ResumeThread(Thread.DangerousGetHandle()); |
| } |
|
|
| public void Dispose() |
| { |
| Process.Dispose(); |
| Thread.Dispose(); |
| GC.SuppressFinalize(this); |
| } |
|
|
| ~ProcessInformation() => Dispose(); |
| } |
|
|
| internal static class ProcessNativeMethods |
| { |
| [DllImport(PinvokeDllNames.GetStdHandleDllName, SetLastError = true)] |
| public static extern IntPtr GetStdHandle(int whichHandle); |
|
|
| [DllImport(PinvokeDllNames.CreateProcessWithLogonWDllName, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] |
| [return: MarshalAs(UnmanagedType.Bool)] |
| internal static extern bool CreateProcessWithLogonW(string userName, |
| string domain, |
| IntPtr password, |
| LogonFlags logonFlags, |
| [MarshalAs(UnmanagedType.LPWStr)] string appName, |
| StringBuilder cmdLine, |
| int creationFlags, |
| IntPtr environmentBlock, |
| [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, |
| STARTUPINFO lpStartupInfo, |
| ref PROCESS_INFORMATION lpProcessInformation); |
|
|
| [DllImport(PinvokeDllNames.CreateProcessDllName, CharSet = CharSet.Unicode, SetLastError = true)] |
| [return: MarshalAs(UnmanagedType.Bool)] |
| public static extern bool CreateProcess([MarshalAs(UnmanagedType.LPWStr)] string lpApplicationName, |
| [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpCommandLine, |
| SECURITY_ATTRIBUTES lpProcessAttributes, |
| SECURITY_ATTRIBUTES lpThreadAttributes, |
| bool bInheritHandles, |
| int dwCreationFlags, |
| IntPtr lpEnvironment, |
| [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, |
| STARTUPINFO lpStartupInfo, |
| ref PROCESS_INFORMATION lpProcessInformation); |
|
|
| [DllImport(PinvokeDllNames.ResumeThreadDllName, CharSet = CharSet.Unicode, SetLastError = true)] |
| public static extern uint ResumeThread(IntPtr threadHandle); |
|
|
| [DllImport("userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] |
| [return: MarshalAs(UnmanagedType.Bool)] |
| public static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit); |
|
|
| [DllImport("userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] |
| [return: MarshalAs(UnmanagedType.Bool)] |
| public static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment); |
|
|
| [Flags] |
| internal enum LogonFlags |
| { |
| LOGON_NETCREDENTIALS_ONLY = 2, |
| LOGON_WITH_PROFILE = 1 |
| } |
|
|
| [StructLayout(LayoutKind.Sequential)] |
| internal struct PROCESS_INFORMATION |
| { |
| public IntPtr hProcess; |
| public IntPtr hThread; |
| public int dwProcessId; |
| public int dwThreadId; |
| } |
|
|
| [StructLayout(LayoutKind.Sequential)] |
| internal sealed class SECURITY_ATTRIBUTES |
| { |
| public int nLength; |
| public SafeLocalMemHandle lpSecurityDescriptor; |
| public bool bInheritHandle; |
|
|
| public SECURITY_ATTRIBUTES() |
| { |
| this.nLength = 12; |
| this.bInheritHandle = true; |
| this.lpSecurityDescriptor = new SafeLocalMemHandle(IntPtr.Zero, true); |
| } |
| } |
|
|
| internal sealed class SafeLocalMemHandle : SafeHandleZeroOrMinusOneIsInvalid |
| { |
| |
| internal SafeLocalMemHandle() |
| : base(true) |
| { |
| } |
|
|
| internal SafeLocalMemHandle(IntPtr existingHandle, bool ownsHandle) |
| : base(ownsHandle) |
| { |
| base.SetHandle(existingHandle); |
| } |
|
|
| [DllImport(PinvokeDllNames.LocalFreeDllName)] |
| private static extern IntPtr LocalFree(IntPtr hMem); |
|
|
| protected override bool ReleaseHandle() |
| { |
| return (LocalFree(base.handle) == IntPtr.Zero); |
| } |
| } |
|
|
| [StructLayout(LayoutKind.Sequential)] |
| internal sealed class STARTUPINFO |
| { |
| public int cb; |
| public IntPtr lpReserved; |
| public IntPtr lpDesktop; |
| public IntPtr lpTitle; |
| public int dwX; |
| public int dwY; |
| public int dwXSize; |
| public int dwYSize; |
| public int dwXCountChars; |
| public int dwYCountChars; |
| public int dwFillAttribute; |
| public int dwFlags; |
| public short wShowWindow; |
| public short cbReserved2; |
| public IntPtr lpReserved2; |
| public SafeFileHandle hStdInput; |
| public SafeFileHandle hStdOutput; |
| public SafeFileHandle hStdError; |
|
|
| public STARTUPINFO() |
| { |
| this.lpReserved = IntPtr.Zero; |
| this.lpDesktop = IntPtr.Zero; |
| this.lpTitle = IntPtr.Zero; |
| this.lpReserved2 = IntPtr.Zero; |
| this.hStdInput = new SafeFileHandle(IntPtr.Zero, false); |
| this.hStdOutput = new SafeFileHandle(IntPtr.Zero, false); |
| this.hStdError = new SafeFileHandle(IntPtr.Zero, false); |
| this.cb = Marshal.SizeOf(this); |
| } |
|
|
| public void Dispose(bool disposing) |
| { |
| if (disposing) |
| { |
| if ((this.hStdInput != null) && !this.hStdInput.IsInvalid) |
| { |
| this.hStdInput.Dispose(); |
| this.hStdInput = null; |
| } |
|
|
| if ((this.hStdOutput != null) && !this.hStdOutput.IsInvalid) |
| { |
| this.hStdOutput.Dispose(); |
| this.hStdOutput = null; |
| } |
|
|
| if ((this.hStdError != null) && !this.hStdError.IsInvalid) |
| { |
| this.hStdError.Dispose(); |
| this.hStdError = null; |
| } |
| } |
| } |
|
|
| public void Dispose() |
| { |
| Dispose(true); |
| } |
| } |
| } |
| #endif |
| #endregion |
|
|
| #region ProcessCommandException |
| |
| |
| |
| public class ProcessCommandException : SystemException |
| { |
| #region ctors |
| |
| |
| |
| |
| public ProcessCommandException() : base() |
| { |
| throw new NotImplementedException(); |
| } |
|
|
| |
| |
| |
| |
| |
| public ProcessCommandException(string message) : base(message) |
| { |
| } |
|
|
| |
| |
| |
| |
| |
| public ProcessCommandException(string message, Exception innerException) |
| : base(message, innerException) |
| { |
| } |
| #endregion ctors |
|
|
| #region Serialization |
| |
| |
| |
| |
| |
| |
| [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] |
| protected ProcessCommandException( |
| SerializationInfo info, |
| StreamingContext context) |
| { |
| throw new NotSupportedException(); |
| } |
|
|
| #endregion Serialization |
|
|
| #region Properties |
| |
| |
| |
| |
| public string ProcessName |
| { |
| get { return _processName; } |
|
|
| set { _processName = value; } |
| } |
|
|
| private string _processName = string.Empty; |
| #endregion Properties |
| } |
|
|
| #endregion ProcessCommandException |
| } |
|
|