File size: 32,927 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Security;
using System.Text;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This cmdlet enters into an interactive session with the specified local process by
/// creating a remote runspace to the process and pushing it on the current PSHost.
/// If the selected process does not contain PowerShell then an error message will result.
/// If the current user does not have sufficient privileges to attach to the selected process
/// then an error message will result.
/// </summary>
[Cmdlet(VerbsCommon.Enter, "PSHostProcess", DefaultParameterSetName = EnterPSHostProcessCommand.ProcessIdParameterSet,
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096580")]
public sealed class EnterPSHostProcessCommand : PSCmdlet
{
#region Members
private IHostSupportsInteractiveSession _interactiveHost;
private RemoteRunspace _connectingRemoteRunspace;
#region Strings
private const string ProcessParameterSet = "ProcessParameterSet";
private const string ProcessNameParameterSet = "ProcessNameParameterSet";
private const string ProcessIdParameterSet = "ProcessIdParameterSet";
private const string PipeNameParameterSet = "PipeNameParameterSet";
private const string PSHostProcessInfoParameterSet = "PSHostProcessInfoParameterSet";
private const string NamedPipeRunspaceName = "PSAttachRunspace";
#endregion
#endregion
#region Parameters
/// <summary>
/// Process to enter.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = EnterPSHostProcessCommand.ProcessParameterSet)]
[ValidateNotNull]
public Process Process
{
get;
set;
}
/// <summary>
/// Id of process to enter.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = EnterPSHostProcessCommand.ProcessIdParameterSet)]
[ValidateRange(0, int.MaxValue)]
public int Id
{
get;
set;
}
/// <summary>
/// Name of process to enter. An error will result if more than one such process exists.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = EnterPSHostProcessCommand.ProcessNameParameterSet)]
[ValidateNotNullOrEmpty]
public string Name
{
get;
set;
}
/// <summary>
/// Host Process Info object that describes a connectible process.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = EnterPSHostProcessCommand.PSHostProcessInfoParameterSet)]
[ValidateNotNull]
public PSHostProcessInfo HostProcessInfo
{
get;
set;
}
/// <summary>
/// Gets or sets the custom named pipe name to connect to. This is usually used in conjunction with `pwsh -CustomPipeName`.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = EnterPSHostProcessCommand.PipeNameParameterSet)]
public string CustomPipeName
{
get;
set;
}
/// <summary>
/// Optional name of AppDomain in process to enter. If not specified then the default AppDomain is used.
/// </summary>
[Parameter(Position = 1, ParameterSetName = EnterPSHostProcessCommand.ProcessParameterSet)]
[Parameter(Position = 1, ParameterSetName = EnterPSHostProcessCommand.ProcessIdParameterSet)]
[Parameter(Position = 1, ParameterSetName = EnterPSHostProcessCommand.ProcessNameParameterSet)]
[Parameter(Position = 1, ParameterSetName = EnterPSHostProcessCommand.PSHostProcessInfoParameterSet)]
[ValidateNotNullOrEmpty]
public string AppDomainName
{
get;
set;
}
#endregion
#region Overrides
/// <summary>
/// End Processing.
/// </summary>
protected override void EndProcessing()
{
// Check if system is in locked down mode, in which case this cmdlet is disabled.
if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
{
WriteError(
new ErrorRecord(
new PSSecurityException(RemotingErrorIdStrings.EnterPSHostProcessCmdletDisabled),
"EnterPSHostProcessCmdletDisabled",
ErrorCategory.SecurityError,
null));
return;
}
// Check for host that supports interactive remote sessions.
_interactiveHost = this.Host as IHostSupportsInteractiveSession;
if (_interactiveHost == null)
{
WriteError(
new ErrorRecord(
new ArgumentException(RemotingErrorIdStrings.HostDoesNotSupportIASession),
"EnterPSHostProcessHostDoesNotSupportIASession",
ErrorCategory.InvalidArgument,
null));
return;
}
// Check selected process for existence, and whether it hosts PowerShell.
Runspace namedPipeRunspace = null;
switch (ParameterSetName)
{
case ProcessIdParameterSet:
Process = GetProcessById(Id);
VerifyProcess(Process);
namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
break;
case ProcessNameParameterSet:
Process = GetProcessByName(Name);
VerifyProcess(Process);
namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
break;
case PSHostProcessInfoParameterSet:
Process = GetProcessByHostProcessInfo(HostProcessInfo);
VerifyProcess(Process);
// Create named pipe runspace for selected process and open.
namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
break;
case PipeNameParameterSet:
VerifyPipeName(CustomPipeName);
namedPipeRunspace = CreateNamedPipeRunspace(CustomPipeName);
break;
}
// Set runspace prompt. The runspace is closed on pop so we don't
// have to reverse this change.
PrepareRunspace(namedPipeRunspace);
try
{
// Push runspace onto host.
_interactiveHost.PushRunspace(namedPipeRunspace);
}
catch (Exception e)
{
namedPipeRunspace.Close();
ThrowTerminatingError(
new ErrorRecord(
e,
"EnterPSHostProcessCannotPushRunspace",
ErrorCategory.InvalidOperation,
this));
}
}
/// <summary>
/// Stop Processing.
/// </summary>
protected override void StopProcessing()
{
RemoteRunspace connectingRunspace = _connectingRemoteRunspace;
connectingRunspace?.AbortOpen();
}
#endregion
#region Private Methods
private Runspace CreateNamedPipeRunspace(string customPipeName)
{
NamedPipeConnectionInfo connectionInfo = new NamedPipeConnectionInfo(customPipeName);
return CreateNamedPipeRunspace(connectionInfo);
}
private Runspace CreateNamedPipeRunspace(int procId, string appDomainName)
{
NamedPipeConnectionInfo connectionInfo = new NamedPipeConnectionInfo(procId, appDomainName);
return CreateNamedPipeRunspace(connectionInfo);
}
private Runspace CreateNamedPipeRunspace(NamedPipeConnectionInfo connectionInfo)
{
TypeTable typeTable = TypeTable.LoadDefaultTypeFiles();
RemoteRunspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo, this.Host, typeTable) as RemoteRunspace;
remoteRunspace.Name = NamedPipeRunspaceName;
remoteRunspace.ShouldCloseOnPop = true;
_connectingRemoteRunspace = remoteRunspace;
try
{
remoteRunspace.Open();
remoteRunspace.Debugger?.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript);
}
catch (RuntimeException e)
{
// Unwrap inner exception for original error message, if any.
string errorMessage = (e.InnerException != null) ? (e.InnerException.Message ?? string.Empty) : string.Empty;
if (connectionInfo.CustomPipeName != null)
{
ThrowTerminatingError(
new ErrorRecord(
new RuntimeException(
StringUtil.Format(
RemotingErrorIdStrings.EnterPSHostProcessCannotConnectToPipe,
connectionInfo.CustomPipeName,
errorMessage),
e.InnerException),
"EnterPSHostProcessCannotConnectToPipe",
ErrorCategory.OperationTimeout,
this));
}
else
{
string msgAppDomainName = connectionInfo.AppDomainName ?? NamedPipeUtils.DefaultAppDomainName;
ThrowTerminatingError(
new ErrorRecord(
new RuntimeException(
StringUtil.Format(
RemotingErrorIdStrings.EnterPSHostProcessCannotConnectToProcess,
msgAppDomainName,
connectionInfo.ProcessId,
errorMessage),
e.InnerException),
"EnterPSHostProcessCannotConnectToProcess",
ErrorCategory.OperationTimeout,
this));
}
}
finally
{
_connectingRemoteRunspace = null;
}
return remoteRunspace;
}
private static void PrepareRunspace(Runspace runspace)
{
string promptFn = StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessPrompt,
@"function global:prompt { """,
@"$($PID)",
@"PS $($executionContext.SessionState.Path.CurrentLocation)> "" }"
);
// Set prompt in pushed named pipe runspace.
using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
{
ps.Runspace = runspace;
try
{
// Set pushed runspace prompt.
ps.AddScript(promptFn).Invoke();
}
catch (Exception)
{
}
}
}
private Process GetProcessById(int procId)
{
var process = PSHostProcessUtils.GetProcessById(procId);
if (process is null)
{
ThrowTerminatingError(
new ErrorRecord(
new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoProcessFoundWithId, procId)),
"EnterPSHostProcessNoProcessFoundWithId",
ErrorCategory.InvalidArgument,
this)
);
}
return process;
}
private Process GetProcessByHostProcessInfo(PSHostProcessInfo hostProcessInfo)
{
return GetProcessById(hostProcessInfo.ProcessId);
}
private Process GetProcessByName(string name)
{
Collection<Process> foundProcesses;
using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
{
ps.AddCommand("Get-Process").AddParameter("Name", name);
foundProcesses = ps.Invoke<Process>();
}
if (foundProcesses.Count == 0)
{
ThrowTerminatingError(
new ErrorRecord(
new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoProcessFoundWithName, name)),
"EnterPSHostProcessNoProcessFoundWithName",
ErrorCategory.InvalidArgument,
this)
);
}
else if (foundProcesses.Count > 1)
{
ThrowTerminatingError(
new ErrorRecord(
new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessMultipleProcessesFoundWithName, name)),
"EnterPSHostProcessMultipleProcessesFoundWithName",
ErrorCategory.InvalidArgument,
this)
);
}
return foundProcesses[0];
}
private void VerifyProcess(Process process)
{
if (process.Id == Environment.ProcessId)
{
ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException(RemotingErrorIdStrings.EnterPSHostProcessCantEnterSameProcess),
"EnterPSHostProcessCantEnterSameProcess",
ErrorCategory.InvalidOperation,
this)
);
}
bool hostsSMA = false;
IReadOnlyCollection<PSHostProcessInfo> availableProcInfo = GetPSHostProcessInfoCommand.GetAppDomainNamesFromProcessId(null);
foreach (var procInfo in availableProcInfo)
{
if (process.Id == procInfo.ProcessId)
{
hostsSMA = true;
break;
}
}
if (!hostsSMA)
{
ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoPowerShell, Process.Id)),
"EnterPSHostProcessNoPowerShell",
ErrorCategory.InvalidOperation,
this)
);
}
}
private void VerifyPipeName(string customPipeName)
{
// Named Pipes are represented differently on Windows vs macOS & Linux
var sb = new StringBuilder(customPipeName.Length);
if (Platform.IsWindows)
{
sb.Append(@"\\.\pipe\");
}
else
{
sb.Append(Path.GetTempPath()).Append("CoreFxPipe_");
}
sb.Append(customPipeName);
string pipePath = sb.ToString();
if (!File.Exists(pipePath))
{
ThrowTerminatingError(
new ErrorRecord(
new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoNamedPipeFound, customPipeName)),
"EnterPSHostProcessNoNamedPipeFound",
ErrorCategory.InvalidArgument,
this));
}
}
#endregion
}
/// <summary>
/// This cmdlet exits an interactive session with a local process.
/// </summary>
[Cmdlet(VerbsCommon.Exit, "PSHostProcess",
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096583")]
public sealed class ExitPSHostProcessCommand : PSCmdlet
{
#region Overrides
/// <summary>
/// Process Record.
/// </summary>
protected override void ProcessRecord()
{
var _interactiveHost = this.Host as IHostSupportsInteractiveSession;
if (_interactiveHost == null)
{
WriteError(
new ErrorRecord(
new ArgumentException(RemotingErrorIdStrings.HostDoesNotSupportIASession),
"ExitPSHostProcessHostDoesNotSupportIASession",
ErrorCategory.InvalidArgument,
null));
return;
}
_interactiveHost.PopRunspace();
}
#endregion
}
/// <summary>
/// This cmdlet returns a collection of PSHostProcessInfo objects containing
/// process and AppDomain name information for processes that have PowerShell loaded.
/// </summary>
[Cmdlet(VerbsCommon.Get, "PSHostProcessInfo", DefaultParameterSetName = GetPSHostProcessInfoCommand.ProcessNameParameterSet,
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=517012")]
[OutputType(typeof(PSHostProcessInfo))]
public sealed class GetPSHostProcessInfoCommand : PSCmdlet
{
#region Strings
private const string ProcessParameterSet = "ProcessParameterSet";
private const string ProcessIdParameterSet = "ProcessIdParameterSet";
private const string ProcessNameParameterSet = "ProcessNameParameterSet";
#if UNIX
// CoreFx uses the system temp path to store the file used for named pipes and is not settable.
// This member is only used by Get-PSHostProcessInfo to know where to look for the named pipe files.
private static readonly string NamedPipePath = Path.GetTempPath();
#else
private const string NamedPipePath = @"\\.\pipe\";
#endif
#endregion
#region Parameters
/// <summary>
/// Name of Process.
/// </summary>
[Parameter(Position = 0, ParameterSetName = GetPSHostProcessInfoCommand.ProcessNameParameterSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[ValidateNotNullOrEmpty]
public string[] Name
{
get;
set;
}
/// <summary>
/// Process.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = GetPSHostProcessInfoCommand.ProcessParameterSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[ValidateNotNullOrEmpty]
public Process[] Process
{
get;
set;
}
/// <summary>
/// Id of process.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = GetPSHostProcessInfoCommand.ProcessIdParameterSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[ValidateNotNullOrEmpty]
public int[] Id
{
get;
set;
}
#endregion
#region Overrides
/// <summary>
/// End bock processing.
/// </summary>
protected override void EndProcessing()
{
IReadOnlyCollection<PSHostProcessInfo> processAppDomainInfo;
switch (ParameterSetName)
{
case ProcessNameParameterSet:
processAppDomainInfo = GetAppDomainNamesFromProcessId(GetProcIdsFromNames(Name));
break;
case ProcessIdParameterSet:
processAppDomainInfo = GetAppDomainNamesFromProcessId(Id);
break;
case ProcessParameterSet:
processAppDomainInfo = GetAppDomainNamesFromProcessId(GetProcIdsFromProcs(Process));
break;
default:
Debug.Fail("Unknown parameter set.");
processAppDomainInfo = new ReadOnlyCollection<PSHostProcessInfo>(new Collection<PSHostProcessInfo>());
break;
}
WriteObject(processAppDomainInfo, true);
}
#endregion
#region Private Methods
private static int[] GetProcIdsFromProcs(Process[] processes)
{
List<int> returnIds = new List<int>();
foreach (Process process in processes)
{
returnIds.Add(process.Id);
}
return returnIds.ToArray();
}
private static int[] GetProcIdsFromNames(string[] names)
{
if ((names == null) || (names.Length == 0))
{
return null;
}
List<int> returnIds = new List<int>();
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses();
foreach (string name in names)
{
WildcardPattern namePattern = WildcardPattern.Get(name, WildcardOptions.IgnoreCase);
foreach (var proc in processes)
{
// Skip processes that have already terminated.
if (proc.HasExited)
{
continue;
}
try
{
if (namePattern.IsMatch(proc.ProcessName))
{
returnIds.Add(proc.Id);
}
}
catch (InvalidOperationException)
{
// Ignore if process has exited in the mean time.
}
}
}
return returnIds.ToArray();
}
#endregion
#region Internal Methods
/// <summary>
/// Returns all named pipe AppDomain names for given process Ids or all PowerShell
/// processes if procIds parameter is null.
/// PowerShell pipe name example:
/// PSHost.130566795082911445.8224.DefaultAppDomain.powershell.
/// </summary>
/// <param name="procIds">Process Ids or null.</param>
/// <returns>Collection of process AppDomain info.</returns>
internal static IReadOnlyCollection<PSHostProcessInfo> GetAppDomainNamesFromProcessId(int[] procIds)
{
var procAppDomainInfo = new List<PSHostProcessInfo>();
// Get all named pipe 'files' on local machine.
List<string> namedPipes = new List<string>();
var namedPipeDirectory = new DirectoryInfo(NamedPipePath);
foreach (var pipeFileInfo in namedPipeDirectory.EnumerateFiles(NamedPipeUtils.NamedPipeNamePrefixSearch))
{
namedPipes.Add(Path.Combine(pipeFileInfo.DirectoryName, pipeFileInfo.Name));
}
// Collect all PowerShell named pipes for given process Ids.
foreach (string namedPipe in namedPipes)
{
int startIndex = namedPipe.IndexOf(NamedPipeUtils.NamedPipeNamePrefix, StringComparison.OrdinalIgnoreCase);
if (startIndex > -1)
{
int pStartTimeIndex = namedPipe.IndexOf('.', startIndex);
if (pStartTimeIndex > -1)
{
int pIdIndex = namedPipe.IndexOf('.', pStartTimeIndex + 1);
if (pIdIndex > -1)
{
int pAppDomainIndex = namedPipe.IndexOf('.', pIdIndex + 1);
if (pAppDomainIndex > -1)
{
ReadOnlySpan<char> idString = namedPipe.AsSpan(pIdIndex + 1, (pAppDomainIndex - pIdIndex - 1));
int id = -1;
if (int.TryParse(idString, out id))
{
// Filter on provided proc Ids.
if (procIds != null)
{
bool found = false;
foreach (int procId in procIds)
{
if (id == procId)
{
found = true;
break;
}
}
if (!found)
{
continue;
}
}
}
else
{
// Process id is not valid so we'll skip
continue;
}
int pNameIndex = namedPipe.IndexOf('.', pAppDomainIndex + 1);
if (pNameIndex > -1)
{
string appDomainName = namedPipe.Substring(pAppDomainIndex + 1, (pNameIndex - pAppDomainIndex - 1));
string pName = namedPipe.Substring(pNameIndex + 1);
Process process = null;
try
{
process = PSHostProcessUtils.GetProcessById(id);
}
catch (Exception)
{
// Do nothing if the process no longer exists
}
if (process == null)
{
try
{
// If the process is gone, try removing the PSHost named pipe
var pipeFile = new FileInfo(namedPipe);
pipeFile.Delete();
}
catch (Exception)
{
// best effort to cleanup
}
}
else
{
try
{
if (process.ProcessName.Equals(pName, StringComparison.Ordinal))
{
// only add if the process name matches
procAppDomainInfo.Add(new PSHostProcessInfo(pName, id, appDomainName, namedPipe));
}
}
catch (InvalidOperationException)
{
// Ignore if process has exited in the mean time.
}
}
}
}
}
}
}
}
if (procAppDomainInfo.Count > 1)
{
// Sort list by process name.
var comparerInfo = CultureInfo.InvariantCulture.CompareInfo;
procAppDomainInfo.Sort((firstItem, secondItem) => comparerInfo.Compare(firstItem.ProcessName, secondItem.ProcessName, CompareOptions.IgnoreCase));
}
return new ReadOnlyCollection<PSHostProcessInfo>(procAppDomainInfo);
}
#endregion
}
#region PSHostProcessInfo class
/// <summary>
/// PowerShell host process information class.
/// </summary>
public sealed class PSHostProcessInfo
{
#region Members
private readonly string _pipeNameFilePath;
#endregion
#region Properties
/// <summary>
/// Name of process.
/// </summary>
public string ProcessName { get; }
/// <summary>
/// Id of process.
/// </summary>
public int ProcessId { get; }
/// <summary>
/// Name of PowerShell AppDomain in process.
/// </summary>
public string AppDomainName { get; }
/// <summary>
/// Main window title of the process.
/// </summary>
public string MainWindowTitle { get; }
#endregion
#region Constructors
private PSHostProcessInfo() { }
/// <summary>
/// Initializes a new instance of the PSHostProcessInfo type.
/// </summary>
/// <param name="processName">Name of process.</param>
/// <param name="processId">Id of process.</param>
/// <param name="appDomainName">Name of process AppDomain.</param>
/// <param name="pipeNameFilePath">File path of pipe name.</param>
internal PSHostProcessInfo(
string processName,
int processId,
string appDomainName,
string pipeNameFilePath)
{
if (string.IsNullOrEmpty(processName))
{
throw new PSArgumentNullException(nameof(processName));
}
if (string.IsNullOrEmpty(appDomainName))
{
throw new PSArgumentNullException(nameof(appDomainName));
}
MainWindowTitle = string.Empty;
try
{
var process = PSHostProcessUtils.GetProcessById(processId);
MainWindowTitle = process?.MainWindowTitle ?? string.Empty;
}
catch (ArgumentException)
{
// Window title is optional.
}
catch (InvalidOperationException)
{
// Window title is optional.
}
this.ProcessName = processName;
this.ProcessId = processId;
this.AppDomainName = appDomainName;
_pipeNameFilePath = pipeNameFilePath;
}
#endregion
#region Methods
/// <summary>
/// Retrieves the pipe name file path.
/// </summary>
/// <returns>Pipe name file path.</returns>
public string GetPipeNameFilePath()
{
return _pipeNameFilePath;
}
#endregion
}
#endregion
#region PSHostProcessUtils
internal static class PSHostProcessUtils
{
/// <summary>
/// Return a System.Diagnostics.Process object by process Id,
/// or null if not found or process has exited.
/// </summary>
/// <param name="procId">Process of Id to find.</param>
/// <returns>Process object or null.</returns>
public static Process GetProcessById(int procId)
{
try
{
var process = Process.GetProcessById(procId);
return process.HasExited ? null : process;
}
catch (System.ArgumentException)
{
return null;
}
}
}
#endregion
}
|