-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessDriveProvider.cs
More file actions
1162 lines (1035 loc) · 43.5 KB
/
ProcessDriveProvider.cs
File metadata and controls
1162 lines (1035 loc) · 43.5 KB
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Net;
using System.Runtime.InteropServices;
namespace ProcessDrive;
#region Output Types
public class ProcessInfo
{
public string Directory { get; set; } = "";
public string Name { get; set; } = "";
public int? PID { get; set; }
public int? ParentPID { get; set; }
public string CommandLine { get; set; } = "";
public double? MemMB { get; set; }
public string CPU { get; set; } = "";
public int? Threads { get; set; }
public int? Handles { get; set; }
public string StartTime { get; set; } = "";
}
public class ProcessDetail : ProcessInfo
{
public double WorkingSetMB { get; set; }
public double PeakWorkingSetMB { get; set; }
public double PrivateBytesMB { get; set; }
public double VirtualSizeMB { get; set; }
public double PeakVirtualSizeMB { get; set; }
public double PagedMemoryMB { get; set; }
public double NonpagedMemoryKB { get; set; }
public double UserCPU { get; set; }
public double KernelCPU { get; set; }
public double TotalCPU { get; set; }
public int SessionId { get; set; }
public int BasePriority { get; set; }
public string PriorityClass { get; set; } = "";
public string Path { get; set; } = "";
public string FileVersion { get; set; } = "";
public string Company { get; set; } = "";
public string Description { get; set; } = "";
public string ProductName { get; set; } = "";
public string RunningTime { get; set; } = "";
public long IOReadOps { get; set; }
public long IOWriteOps { get; set; }
public long IOOtherOps { get; set; }
public double IOReadBytesMB { get; set; }
public double IOWriteBytesMB { get; set; }
public double IOOtherBytesMB { get; set; }
public long PageFaults { get; set; }
}
public class ModuleInfo
{
public string Directory { get; set; } = "";
public string Name { get; set; } = "";
public double SizeKB { get; set; }
public string Path { get; set; } = "";
public string Version { get; set; } = "";
public string Company { get; set; } = "";
public string Description { get; set; } = "";
}
public class ThreadInfo
{
public string Directory { get; set; } = "";
public int TID { get; set; }
public string State { get; set; } = "";
public string WaitReason { get; set; } = "";
public int Priority { get; set; }
public double CPU { get; set; }
public string StartTime { get; set; } = "";
public string StartAddress { get; set; } = "";
}
public class ServiceInfo
{
public string Directory { get; set; } = "";
public string Name { get; set; } = "";
public string DisplayName { get; set; } = "";
public string State { get; set; } = "";
public string StartMode { get; set; } = "";
}
public class NetworkInfo
{
public string Directory { get; set; } = "";
public string Protocol { get; set; } = "";
public string LocalAddress { get; set; } = "";
public string RemoteAddress { get; set; } = "";
public string State { get; set; } = "";
}
#endregion
enum PathType { Root, Process, VirtualFolder, VirtualItem }
sealed record PathInfo(PathType Type, int Pid, string? VirtualFolder, string? VirtualItem);
[CmdletProvider("ProcessDrive", ProviderCapabilities.ShouldProcess)]
[OutputType(typeof(ProcessInfo), ProviderCmdlet = ProviderCmdlet.GetChildItem)]
[OutputType(typeof(ModuleInfo), ProviderCmdlet = ProviderCmdlet.GetChildItem)]
[OutputType(typeof(ThreadInfo), ProviderCmdlet = ProviderCmdlet.GetChildItem)]
[OutputType(typeof(ServiceInfo), ProviderCmdlet = ProviderCmdlet.GetChildItem)]
[OutputType(typeof(NetworkInfo), ProviderCmdlet = ProviderCmdlet.GetChildItem)]
[OutputType(typeof(ProcessDetail), ProviderCmdlet = ProviderCmdlet.GetItem)]
[OutputType(typeof(ModuleInfo), ProviderCmdlet = ProviderCmdlet.GetItem)]
[OutputType(typeof(ThreadInfo), ProviderCmdlet = ProviderCmdlet.GetItem)]
[OutputType(typeof(ServiceInfo), ProviderCmdlet = ProviderCmdlet.GetItem)]
public class ProcessDriveProvider : NavigationCmdletProvider
{
private const char Sep = '\\';
private static readonly HashSet<string> VirtualFolderNames = new(StringComparer.OrdinalIgnoreCase)
{
"Modules", "Threads", "Services", "Network"
};
private static readonly Dictionary<string, string> VirtualFolderDescriptions = new(StringComparer.OrdinalIgnoreCase)
{
["Modules"] = "Loaded DLLs and modules",
["Threads"] = "Process threads",
["Services"] = "Associated Windows services",
["Network"] = "Network connections (TCP/UDP)"
};
#region Path Helpers
private static string[] SplitPath(string path)
{
if (string.IsNullOrEmpty(path))
return Array.Empty<string>();
// Strip drive prefix (e.g., "Proc:\")
if (path.Contains(':'))
path = path[(path.IndexOf(':') + 1)..];
return path.Trim(Sep).Split(Sep, StringSplitOptions.RemoveEmptyEntries);
}
private static int ParsePid(string segment)
{
int i = segment.LastIndexOf('_');
if (i >= 0 && int.TryParse(segment.AsSpan(i + 1), out int pid))
return pid;
return -1;
}
private static string FormatSegment(int pid, string name) => $"{name}_{pid}";
private static bool IsRootPath(string path)
{
if (string.IsNullOrEmpty(path)) return true;
var trimmed = path.Trim(Sep);
if (trimmed.Length == 0) return true;
// Handle "Proc:" or "Proc:\" style root
if (trimmed.EndsWith(':')) return true;
return false;
}
private static string BuildChildPath(string parentPath, string childSegment)
=> parentPath.TrimEnd(Sep) + Sep + childSegment;
private string EnsureDrivePrefix(string path)
{
if (PSDriveInfo == null) return path;
var prefix = PSDriveInfo.Name + ":\\";
if (path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
return path;
if (IsRootPath(path))
return prefix;
// Strip drive prefix from internal path if present, then re-add
var inner = path;
if (inner.Contains(':'))
inner = inner[(inner.IndexOf(':') + 1)..];
return prefix + inner.TrimStart(Sep);
}
private PathInfo ParsePathInfo(string path)
{
if (IsRootPath(path)) return new(PathType.Root, -1, null, null);
var segments = SplitPath(path);
var last = segments[^1];
if (VirtualFolderNames.Contains(last))
{
int pid = segments.Length >= 2 ? ParsePid(segments[^2]) : -1;
return new(PathType.VirtualFolder, pid, last, null);
}
// Virtual item (inside a virtual folder) — check BEFORE process to avoid
// misinterpreting items like "12632" or "kernel32.dll" as process nodes
if (segments.Length >= 2 && VirtualFolderNames.Contains(segments[^2]))
{
int pid = segments.Length >= 3 ? ParsePid(segments[^3]) : -1;
return new(PathType.VirtualItem, pid, segments[^2], last);
}
int lastPid = ParsePid(last);
if (lastPid >= 0)
return new(PathType.Process, lastPid, null, null);
// Unrecognized path — ItemExists will return false (Pid < 0)
return new(PathType.VirtualItem, -1, null, null);
}
#endregion
#region Process Tree
private sealed record ProcInfo(int Pid, int ParentPid, string Name, string CommandLine,
long WorkingSetSize, int ThreadCount, int HandleCount, string CreationDate, double CpuSeconds);
private static readonly TimeSpan CacheTtl = TimeSpan.FromSeconds(10);
private static void InvalidateCache()
{
lock (_cacheLock)
{
// Skip if cache was just rebuilt (prevents hundreds of WMI queries during recursive wildcard resolution)
if ((DateTime.UtcNow - _cacheTime).TotalSeconds > 1)
_cacheTime = DateTime.MinValue;
}
}
private static DateTime _cacheTime;
private static (Dictionary<int, ProcInfo> map, Dictionary<int, List<int>> children, List<int> roots) _cache;
private static readonly object _cacheLock = new();
private (Dictionary<int, ProcInfo> map, Dictionary<int, List<int>> children, List<int> roots) BuildTree()
{
lock (_cacheLock)
{
if (_cache.map != null && (DateTime.UtcNow - _cacheTime) < CacheTtl)
return _cache;
var map = new Dictionary<int, ProcInfo>();
var children = new Dictionary<int, List<int>>();
using var searcher = new ManagementObjectSearcher(
"SELECT ProcessId, ParentProcessId, Name, CommandLine, " +
"WorkingSetSize, ThreadCount, HandleCount, CreationDate, " +
"KernelModeTime, UserModeTime FROM Win32_Process");
foreach (ManagementObject obj in searcher.Get())
{
int pid = Convert.ToInt32(obj["ProcessId"]);
int ppid = Convert.ToInt32(obj["ParentProcessId"]);
string name = obj["Name"]?.ToString() ?? "unknown";
string cmdLine = obj["CommandLine"]?.ToString() ?? "";
long ws = Convert.ToInt64(obj["WorkingSetSize"] ?? 0);
int threads = Convert.ToInt32(obj["ThreadCount"] ?? 0);
int handles = Convert.ToInt32(obj["HandleCount"] ?? 0);
string creation = obj["CreationDate"]?.ToString() ?? "";
// KernelModeTime + UserModeTime are in 100-nanosecond units
long kernel = Convert.ToInt64(obj["KernelModeTime"] ?? 0);
long user = Convert.ToInt64(obj["UserModeTime"] ?? 0);
double cpuSeconds = Math.Round((kernel + user) / 10_000_000.0, 1);
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
name = name[..^4];
map[pid] = new ProcInfo(pid, ppid, name, cmdLine, ws, threads, handles, creation, cpuSeconds);
}
foreach (var proc in map.Values)
{
if (proc.Pid == proc.ParentPid) continue;
if (!children.ContainsKey(proc.ParentPid))
children[proc.ParentPid] = new List<int>();
children[proc.ParentPid].Add(proc.Pid);
}
var roots = map.Values
.Where(p => !map.ContainsKey(p.ParentPid) || p.ParentPid == p.Pid)
.Select(p => p.Pid)
.ToList();
_cache = (map, children, roots);
_cacheTime = DateTime.UtcNow;
return _cache;
}
}
#endregion
#region Object Factories
private static ProcessInfo CreateProcessInfo(ProcInfo info, string directory) => new()
{
Directory = directory,
Name = info.Name,
PID = info.Pid,
ParentPID = info.ParentPid,
CommandLine = info.CommandLine,
MemMB = Math.Round(info.WorkingSetSize / 1048576.0, 1),
CPU = info.CpuSeconds > 0 ? info.CpuSeconds.ToString() : "",
Threads = info.ThreadCount,
Handles = info.HandleCount,
StartTime = FormatWmiDateTime(info.CreationDate)
};
private static string FormatWmiDateTime(string wmiDate)
{
if (wmiDate.Length >= 14 &&
DateTime.TryParseExact(wmiDate[..14], "yyyyMMddHHmmss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out var dt))
return dt.ToString("yyyy/MM/dd HH:mm:ss");
return "N/A";
}
private static ProcessDetail CreateProcessDetail(ProcInfo info, string directory)
{
var detail = new ProcessDetail
{
Directory = directory,
Name = info.Name,
PID = info.Pid,
ParentPID = info.ParentPid,
CommandLine = info.CommandLine,
MemMB = Math.Round(info.WorkingSetSize / 1048576.0, 1),
CPU = info.CpuSeconds > 0 ? info.CpuSeconds.ToString() : "",
Threads = info.ThreadCount,
Handles = info.HandleCount,
StartTime = FormatWmiDateTime(info.CreationDate)
};
try
{
var proc = Process.GetProcessById(info.Pid);
try
{
detail.CPU = Math.Round(proc.TotalProcessorTime.TotalSeconds, 1).ToString();
detail.UserCPU = Math.Round(proc.UserProcessorTime.TotalSeconds, 2);
detail.KernelCPU = Math.Round(proc.PrivilegedProcessorTime.TotalSeconds, 2);
detail.TotalCPU = Math.Round(proc.TotalProcessorTime.TotalSeconds, 2);
}
catch { }
detail.WorkingSetMB = Math.Round(proc.WorkingSet64 / 1048576.0, 1);
detail.PeakWorkingSetMB = Math.Round(proc.PeakWorkingSet64 / 1048576.0, 1);
detail.PrivateBytesMB = Math.Round(proc.PrivateMemorySize64 / 1048576.0, 1);
detail.VirtualSizeMB = Math.Round(proc.VirtualMemorySize64 / 1048576.0, 1);
detail.PeakVirtualSizeMB = Math.Round(proc.PeakVirtualMemorySize64 / 1048576.0, 1);
detail.PagedMemoryMB = Math.Round(proc.PagedMemorySize64 / 1048576.0, 1);
detail.NonpagedMemoryKB = Math.Round(proc.NonpagedSystemMemorySize64 / 1024.0, 1);
detail.SessionId = proc.SessionId;
detail.BasePriority = proc.BasePriority;
try { detail.PriorityClass = proc.PriorityClass.ToString(); }
catch { detail.PriorityClass = "N/A"; }
try
{
var mainModule = proc.MainModule;
if (mainModule != null)
{
detail.Path = mainModule.FileName;
var vi = mainModule.FileVersionInfo;
detail.FileVersion = vi.FileVersion ?? "";
detail.Company = vi.CompanyName ?? "";
detail.Description = vi.FileDescription ?? "";
detail.ProductName = vi.ProductName ?? "";
}
}
catch { }
try
{
var running = DateTime.Now - proc.StartTime;
detail.RunningTime = $"{(int)running.TotalDays}d {running.Hours}h {running.Minutes}m";
}
catch { }
}
catch { }
try
{
using var searcher = new ManagementObjectSearcher(
$"SELECT ReadOperationCount, WriteOperationCount, OtherOperationCount, " +
$"ReadTransferCount, WriteTransferCount, OtherTransferCount, " +
$"PageFaults FROM Win32_Process WHERE ProcessId = {info.Pid}");
foreach (ManagementObject obj in searcher.Get())
{
detail.IOReadOps = Convert.ToInt64(obj["ReadOperationCount"]);
detail.IOWriteOps = Convert.ToInt64(obj["WriteOperationCount"]);
detail.IOOtherOps = Convert.ToInt64(obj["OtherOperationCount"]);
detail.IOReadBytesMB = Math.Round(Convert.ToInt64(obj["ReadTransferCount"]) / 1048576.0, 1);
detail.IOWriteBytesMB = Math.Round(Convert.ToInt64(obj["WriteTransferCount"]) / 1048576.0, 1);
detail.IOOtherBytesMB = Math.Round(Convert.ToInt64(obj["OtherTransferCount"]) / 1048576.0, 1);
detail.PageFaults = Convert.ToInt64(obj["PageFaults"]);
}
}
catch { }
return detail;
}
private static ProcessInfo CreateVirtualFolderInfo(string name, string directory) => new()
{
Directory = directory,
Name = $"[{name}]",
StartTime = VirtualFolderDescriptions.GetValueOrDefault(name, "")
};
private static ModuleInfo CreateModuleInfo(ProcessModule mod, string directory)
{
var info = new ModuleInfo
{
Directory = directory,
Name = mod.ModuleName,
SizeKB = Math.Round(mod.ModuleMemorySize / 1024.0, 1),
Path = mod.FileName
};
try
{
var vi = mod.FileVersionInfo;
info.Version = vi.FileVersion ?? "";
info.Company = vi.CompanyName ?? "";
info.Description = vi.FileDescription ?? "";
}
catch { }
return info;
}
private static ThreadInfo CreateThreadInfo(ProcessThread thread, string directory)
{
var info = new ThreadInfo { Directory = directory, TID = thread.Id };
try { info.State = thread.ThreadState.ToString(); } catch { info.State = "N/A"; }
try { info.WaitReason = thread.ThreadState == System.Diagnostics.ThreadState.Wait ? thread.WaitReason.ToString() : ""; }
catch { }
info.Priority = thread.CurrentPriority;
try { info.CPU = Math.Round(thread.TotalProcessorTime.TotalSeconds, 2); } catch { }
try { info.StartTime = thread.StartTime.ToString("yyyy/MM/dd HH:mm:ss"); } catch { info.StartTime = "N/A"; }
try { info.StartAddress = $"0x{thread.StartAddress:X}"; } catch { info.StartAddress = "N/A"; }
return info;
}
private static ServiceInfo CreateServiceInfo(ManagementObject svc, string directory) => new()
{
Directory = directory,
Name = svc["Name"]?.ToString() ?? "",
DisplayName = svc["DisplayName"]?.ToString() ?? "",
State = svc["State"]?.ToString() ?? "",
StartMode = svc["StartMode"]?.ToString() ?? ""
};
private static NetworkInfo CreateNetworkInfo(string protocol, string localAddr, int localPort,
string remoteAddr, int remotePort, string state, string directory) => new()
{
Directory = directory,
Protocol = protocol,
LocalAddress = $"{localAddr}:{localPort}",
RemoteAddress = remoteAddr.Length > 0 ? $"{remoteAddr}:{remotePort}" : "",
State = state
};
#endregion
#region Virtual Folder Data & Cache
private static readonly Dictionary<int, (List<ModuleInfo> data, DateTime time)> _moduleCache = new();
private static readonly Dictionary<int, (List<ServiceInfo> data, DateTime time)> _serviceCache = new();
private static readonly object _vfCacheLock = new();
private static List<T>? GetVfCache<T>(Dictionary<int, (List<T> data, DateTime time)> cache, int pid)
{
lock (_vfCacheLock)
{
if (cache.TryGetValue(pid, out var entry) && (DateTime.UtcNow - entry.time) < CacheTtl)
return entry.data;
return null;
}
}
private static void SetVfCache<T>(Dictionary<int, (List<T> data, DateTime time)> cache, int pid, List<T> data)
{
lock (_vfCacheLock) { cache[pid] = (data, DateTime.UtcNow); }
}
private void WriteModules(int pid, string parentPath)
{
var directory = EnsureDrivePrefix(parentPath);
try
{
var cached = Force ? null : GetVfCache(_moduleCache, pid);
if (cached == null)
{
cached = new List<ModuleInfo>();
var proc = Process.GetProcessById(pid);
foreach (ProcessModule mod in proc.Modules)
cached.Add(CreateModuleInfo(mod, directory));
SetVfCache(_moduleCache, pid, cached);
}
foreach (var mod in cached)
{
mod.Directory = directory;
WriteItemObject(mod, BuildChildPath(parentPath, mod.Name), false);
}
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, "GetModulesFailed", ErrorCategory.PermissionDenied, pid));
}
}
private void WriteThreads(int pid, string parentPath)
{
var directory = EnsureDrivePrefix(parentPath);
try
{
var proc = Process.GetProcessById(pid);
foreach (ProcessThread thread in proc.Threads)
{
var segment = thread.Id.ToString();
var itemPath = BuildChildPath(parentPath, segment);
WriteItemObject(CreateThreadInfo(thread, directory), itemPath, false);
}
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, "GetThreadsFailed", ErrorCategory.PermissionDenied, pid));
}
}
private void WriteServices(int pid, string parentPath)
{
var directory = EnsureDrivePrefix(parentPath);
try
{
var cached = Force ? null : GetVfCache(_serviceCache, pid);
if (cached == null)
{
cached = new List<ServiceInfo>();
using var searcher = new ManagementObjectSearcher(
$"SELECT Name, DisplayName, State, StartMode FROM Win32_Service WHERE ProcessId = {pid}");
foreach (ManagementObject svc in searcher.Get())
cached.Add(CreateServiceInfo(svc, directory));
SetVfCache(_serviceCache, pid, cached);
}
foreach (var svc in cached)
{
svc.Directory = directory;
WriteItemObject(svc, BuildChildPath(parentPath, svc.Name), false);
}
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, "GetServicesFailed", ErrorCategory.PermissionDenied, pid));
}
}
private void WriteNetwork(int pid, string parentPath)
{
var directory = EnsureDrivePrefix(parentPath);
try
{
// TCP connections
foreach (var conn in NetworkHelper.GetTcpConnections(pid))
{
var segment = $"TCP_{conn.LocalAddr}_{conn.LocalPort}";
var itemPath = BuildChildPath(parentPath, segment);
WriteItemObject(CreateNetworkInfo("TCP", conn.LocalAddr, conn.LocalPort,
conn.RemoteAddr, conn.RemotePort, conn.State, directory), itemPath, false);
}
// UDP listeners
foreach (var conn in NetworkHelper.GetUdpListeners(pid))
{
var segment = $"UDP_{conn.LocalAddr}_{conn.LocalPort}";
var itemPath = BuildChildPath(parentPath, segment);
WriteItemObject(CreateNetworkInfo("UDP", conn.LocalAddr, conn.LocalPort,
"", 0, "", directory), itemPath, false);
}
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, "GetNetworkFailed", ErrorCategory.PermissionDenied, pid));
}
}
private void WriteVirtualItem(int pid, string folder, string itemName, string path, string directory)
{
try
{
switch (folder.ToLowerInvariant())
{
case "modules":
var proc = Process.GetProcessById(pid);
foreach (ProcessModule mod in proc.Modules)
{
if (string.Equals(mod.ModuleName, itemName, StringComparison.OrdinalIgnoreCase))
{
WriteItemObject(CreateModuleInfo(mod, directory), path, false);
return;
}
}
break;
case "threads":
if (int.TryParse(itemName, out int tid))
{
var proc2 = Process.GetProcessById(pid);
foreach (ProcessThread t in proc2.Threads)
{
if (t.Id == tid)
{
WriteItemObject(CreateThreadInfo(t, directory), path, false);
return;
}
}
}
break;
case "services":
using (var searcher = new ManagementObjectSearcher(
$"SELECT Name, DisplayName, State, StartMode FROM Win32_Service WHERE ProcessId = {pid} AND Name = '{itemName}'"))
{
foreach (ManagementObject svc in searcher.Get())
{
WriteItemObject(CreateServiceInfo(svc, directory), path, false);
return;
}
}
break;
case "network":
// Parse segment: "TCP_192.168.0.18_53610" → protocol + addr + port
var parts = itemName.Split('_', 3);
if (parts.Length >= 3 && int.TryParse(parts[2], out int port))
{
var protocol = parts[0];
var addr = parts[1];
if (protocol.Equals("TCP", StringComparison.OrdinalIgnoreCase))
{
foreach (var conn in NetworkHelper.GetTcpConnections(pid))
{
if (conn.LocalAddr == addr && conn.LocalPort == port)
{
WriteItemObject(CreateNetworkInfo("TCP", conn.LocalAddr, conn.LocalPort,
conn.RemoteAddr, conn.RemotePort, conn.State, directory), path, false);
return;
}
}
}
else if (protocol.Equals("UDP", StringComparison.OrdinalIgnoreCase))
{
foreach (var conn in NetworkHelper.GetUdpListeners(pid))
{
if (conn.LocalAddr == addr && conn.LocalPort == port)
{
WriteItemObject(CreateNetworkInfo("UDP", conn.LocalAddr, conn.LocalPort,
"", 0, "", directory), path, false);
return;
}
}
}
}
break;
}
}
catch { }
}
#endregion
#region Navigation
protected override bool IsValidPath(string path) => true;
protected override bool ItemExists(string path)
{
var info = ParsePathInfo(path);
switch (info.Type)
{
case PathType.Root:
return true;
case PathType.Process:
var (map, _, _) = BuildTree();
return map.ContainsKey(info.Pid);
case PathType.VirtualFolder:
if (info.Pid < 0) return false;
var (map2, _, _) = BuildTree();
return map2.ContainsKey(info.Pid);
case PathType.VirtualItem:
return info.Pid >= 0;
default:
return false;
}
}
protected override bool IsItemContainer(string path)
{
var info = ParsePathInfo(path);
return info.Type != PathType.VirtualItem;
}
protected override void GetItem(string path)
{
var info = ParsePathInfo(path);
var directory = EnsureDrivePrefix(path);
switch (info.Type)
{
case PathType.Root:
var (map, _, _) = BuildTree();
var pso = new PSObject();
pso.Properties.Add(new PSNoteProperty("Description", "Process Tree Root"));
pso.Properties.Add(new PSNoteProperty("TotalProcesses", map.Count));
WriteItemObject(pso, path, true);
break;
case PathType.Process:
var (map2, _, _) = BuildTree();
if (map2.TryGetValue(info.Pid, out var procInfo))
WriteItemObject(CreateProcessDetail(procInfo, directory), path, true);
break;
case PathType.VirtualFolder:
WriteItemObject(CreateVirtualFolderInfo(info.VirtualFolder!, directory), path, true);
break;
case PathType.VirtualItem:
if (info.Pid >= 0 && info.VirtualFolder != null && info.VirtualItem != null)
WriteVirtualItem(info.Pid, info.VirtualFolder, info.VirtualItem, path, directory);
break;
}
}
protected override void GetChildItems(string path, bool recurse)
{
if (Force) InvalidateCache();
var info = ParsePathInfo(path);
switch (info.Type)
{
case PathType.Root:
{
var (map, children, roots) = BuildTree();
var directory = EnsureDrivePrefix(path);
var sorted = SortChildPids(roots, map);
WriteImmediateChildren(path, directory, sorted, map);
if (recurse)
RecurseChildren(path, sorted, map, children);
break;
}
case PathType.Process:
{
var (map, children, _) = BuildTree();
var childPids = children.TryGetValue(info.Pid, out var c) ? c : new List<int>();
var directory = EnsureDrivePrefix(path);
var sorted = SortChildPids(childPids, map);
// First pass: write immediate child processes
WriteImmediateChildren(path, directory, sorted, map);
// Write virtual folders (same Directory group as child processes)
foreach (var folder in VirtualFolderNames.Order())
{
var folderPath = BuildChildPath(path, folder);
WriteItemObject(CreateVirtualFolderInfo(folder, directory), folderPath, true);
}
// Second pass: recurse into children
if (recurse)
RecurseChildren(path, sorted, map, children);
break;
}
case PathType.VirtualFolder:
{
if (info.Pid < 0) break;
switch (info.VirtualFolder!.ToLowerInvariant())
{
case "modules": WriteModules(info.Pid, path); break;
case "threads": WriteThreads(info.Pid, path); break;
case "services": WriteServices(info.Pid, path); break;
case "network": WriteNetwork(info.Pid, path); break;
}
break;
}
}
}
private static List<int> SortChildPids(List<int> childPids,
Dictionary<int, ProcInfo> map)
{
return childPids
.Where(p => map.ContainsKey(p))
.OrderBy(p => map[p].Name)
.ToList();
}
private void WriteImmediateChildren(string parentPath, string directory, List<int> sortedPids,
Dictionary<int, ProcInfo> map)
{
foreach (int cpid in sortedPids)
{
var info = map[cpid];
var childPath = BuildChildPath(parentPath, FormatSegment(cpid, info.Name));
WriteItemObject(CreateProcessInfo(info, directory), childPath, true);
}
}
private void RecurseChildren(string parentPath, List<int> sortedPids,
Dictionary<int, ProcInfo> map, Dictionary<int, List<int>> children)
{
foreach (int cpid in sortedPids)
{
if (!children.TryGetValue(cpid, out var grandKids) || grandKids.Count == 0)
continue;
var info = map[cpid];
var childPath = BuildChildPath(parentPath, FormatSegment(cpid, info.Name));
var childDirectory = EnsureDrivePrefix(childPath);
var sortedGrandKids = SortChildPids(grandKids, map);
WriteImmediateChildren(childPath, childDirectory, sortedGrandKids, map);
RecurseChildren(childPath, sortedGrandKids, map, children);
}
}
protected override void GetChildNames(string path, ReturnContainers returnContainers)
{
if (Force) InvalidateCache();
var info = ParsePathInfo(path);
switch (info.Type)
{
case PathType.Root:
{
var (map, _, roots) = BuildTree();
foreach (int pid in roots.OrderBy(p => map.TryGetValue(p, out var i) ? i.Name : ""))
{
if (!map.TryGetValue(pid, out var pi)) continue;
var segment = FormatSegment(pid, pi.Name);
WriteItemObject(segment, BuildChildPath(path, segment), true);
}
break;
}
case PathType.Process:
{
var (map, children, _) = BuildTree();
var childPids = children.TryGetValue(info.Pid, out var c) ? c : new List<int>();
// Child process names
foreach (int cpid in childPids.OrderBy(p => map.TryGetValue(p, out var i) ? i.Name : ""))
{
if (!map.TryGetValue(cpid, out var pi)) continue;
var segment = FormatSegment(cpid, pi.Name);
WriteItemObject(segment, BuildChildPath(path, segment), true);
}
// Virtual folder names are NOT listed here.
// Tab completion uses GetChildItems (not GetChildNames), so cd Mod<Tab> still works.
// Excluding them prevents recursive wildcard (dir note* -Recurse) from entering virtual folders.
break;
}
case PathType.VirtualFolder:
{
if (info.Pid < 0) break;
try
{
switch (info.VirtualFolder!.ToLowerInvariant())
{
case "modules":
var modules = GetVfCache(_moduleCache, info.Pid);
if (modules != null)
{
foreach (var mod in modules)
WriteItemObject(mod.Name, BuildChildPath(path, mod.Name), false);
}
else
{
var proc = Process.GetProcessById(info.Pid);
foreach (ProcessModule mod in proc.Modules)
WriteItemObject(mod.ModuleName, BuildChildPath(path, mod.ModuleName), false);
}
break;
case "threads":
var proc2 = Process.GetProcessById(info.Pid);
foreach (ProcessThread t in proc2.Threads)
{
var seg = t.Id.ToString();
WriteItemObject(seg, BuildChildPath(path, seg), false);
}
break;
case "services":
var services = GetVfCache(_serviceCache, info.Pid);
if (services != null)
{
foreach (var svc in services)
WriteItemObject(svc.Name, BuildChildPath(path, svc.Name), false);
}
else
{
using var searcher = new ManagementObjectSearcher(
$"SELECT Name FROM Win32_Service WHERE ProcessId = {info.Pid}");
foreach (ManagementObject svc in searcher.Get())
{
var name = svc["Name"]?.ToString() ?? "";
WriteItemObject(name, BuildChildPath(path, name), false);
}
}
break;
case "network":
foreach (var conn in NetworkHelper.GetTcpConnections(info.Pid))
{
var seg = $"TCP_{conn.LocalAddr}_{conn.LocalPort}";
WriteItemObject(seg, BuildChildPath(path, seg), false);
}
foreach (var conn in NetworkHelper.GetUdpListeners(info.Pid))
{
var seg = $"UDP_{conn.LocalAddr}_{conn.LocalPort}";
WriteItemObject(seg, BuildChildPath(path, seg), false);
}
break;
}
}
catch { /* process may have exited */ }
break;
}
}
}
protected override bool HasChildItems(string path)
{
var info = ParsePathInfo(path);
return info.Type switch
{
PathType.Root => true,
PathType.Process => true, // always has virtual folders at minimum
PathType.VirtualFolder => true, // safe: virtual folders are excluded from GetChildNames
_ => false
};
}
#endregion
#region Path Manipulation
protected override string MakePath(string parent, string child)
{
var result = base.MakePath(parent, child);
if (result.EndsWith(Sep) && result.Length > 1 && result[^2] != ':')
result = result[..^1];
return result;
}
protected override string NormalizeRelativePath(string path, string basePath)
{
var result = base.NormalizeRelativePath(path, basePath);
if (result.StartsWith(Sep) && result.Length > 1)
result = result[1..];
// Canonicalize virtual folder name casing (e.g. "network" → "Network")
var parts = result.Split(Sep);
for (int i = 0; i < parts.Length; i++)
{
foreach (var folder in VirtualFolderNames)
{
if (string.Equals(parts[i], folder, StringComparison.OrdinalIgnoreCase))
{
parts[i] = folder;
break;
}
}
}
return string.Join(Sep, parts);
}
#endregion
#region Actions
protected override void RemoveItem(string path, bool recurse)
{
var info = ParsePathInfo(path);
if (info.Type != PathType.Process || info.Pid <= 0) return;
var segments = SplitPath(path);
if (!ShouldProcess($"Process {segments[^1]} (PID: {info.Pid})", "Stop"))
return;
try
{
var proc = Process.GetProcessById(info.Pid);
if (recurse)
proc.Kill(true);
else
proc.Kill();
WriteItemObject($"Stopped process {info.Pid}", path, false);
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, "StopProcessFailed",
ErrorCategory.InvalidOperation, info.Pid));
}
}
#endregion