Powershell异常问题

Powershell Exception issue

提前感谢您考虑这样愚蠢的查询。 我正在尝试使用以下查询从 powershell 获取具有一些扩展属性的进程列表:

**Get-Process -FileVersionInfo | select -Unique | Select-Object * | Format-Table -Property OriginalFilename, FileName, InternalName, ProductName, CompanyName, FileVersion -Wrap > C:\Users\user\OneDrive\Desktop\final.txt**

它可以工作,但对于某些进程,我无法获得 FileVersion,这没问题,我不关心这个。问题是即使试图捕获异常,它也什么都不做。

Get-Process: Cannot enumerate the file version information of the "csrss" process. At line:1 char:7

  • try { Get-Process -FileVersionInfo | select -Unique | Select-Object * ...
  •   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : PermissionDenied: (System.Diagnostics.Process (csrss):Process) [Get-Process], ProcessCommandException
    • FullyQualifiedErrorId : CouldnotEnumerateFileVer,Microsoft.PowerShell.Commands.GetProcessCommand

试图通过

获取异常详细信息
**$Error[0] | Select-Property ***

**$Error[0].exception.GetType().fullname**

结果如下:

WriteErrorStream : True PSMessageDetails : Exception
: Microsoft.PowerShell.Commands.ProcessCommandException: Cannot enumerate the file version information of the "Idle" process. ---> System.ComponentModel.Win32Exception: Unable to enumerate the process modules. at System.Diagnostics.NtProcessManager.GetModuleInfos(Int32 processId, Boolean firstModuleOnly) at System.Diagnostics.NtProcessManager.GetFirstModuleInfo(Int32 processId) at System.Diagnostics.Process.get_MainModule() at System.Management.Automation.PsUtils.GetMainModule(Process targetProcess) at Microsoft.PowerShell.Commands.GetProcessCommand.ProcessRecord() --- End of inner exception stack trace --- TargetObject : System.Diagnostics.Process (Idle) CategoryInfo : PermissionDenied: (System.Diagnostics.Process (Idle):Process) [Get-Process], ProcessCommandException FullyQualifiedErrorId : CouldnotEnumerateFileVer,Microsoft.PowerShell.Commands.GetProcessCommand ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo ScriptStackTrace : at , : line 1 PipelineIterationInfo : {0, 1, 64, 0...}

虽然试图用 [Microsoft.PowerShell.Commands.ProcessCommandException] 捕获异常,但它什么也不做,仍然在红线上抛出一堆。

try { Get-Process -FileVersionInfo | select -Unique | Select-Object * | Format-Table -Property OriginalFilename, FileName, InternalName, ProductName, CompanyName, FileVersion -Wrap > C:\Users\user\OneDrive\Desktop\final.txt 
} catch [Microsoft.PowerShell.Commands.ProcessCommandException] { 
Write-Verbose "Catch all" -Verbose
}

你能帮忙吗? 提前致谢。

您可以通过向 Get-Process 添加 ErrorAction 来忽略您没有所需访问权限的进程

Get-Process -FileVersionInfo -ErrorAction Ignore

如果您确实需要知道哪些进程给您带来了错误,您可以使用

Get-Process -FileVersionInfo -ErrorAction SilentlyContinue

然后查看 $errorcudo 到 @zett42

Get-Process -FileVersionInfo -ErrorAction SilentlyContinue -ErrorVariable ProcError

然后再看$ProcError