如何解决修改在 Stack Overflow 上找到的 PowerShell 脚本
我在 Stack Overflow 上找到了 Get-ProcessPlus 的 PMental 脚本。在zett42的帮助下 和其他几个我设法让它运行(对 PS 来说非常新)。谢谢你们,它拥有我真正想要的一切。 我也选择了看看是否可以让脚本再添加一项功能。我也希望它返回进程的命令行值。我让它部分工作。通过我的修改,它仍然以默认方式运行,并按 ID 运行,但不再按名称运行。我已经做了很多阅读,但仍然无法正常工作。这是代码和我的模组。任何帮助将不胜感激。
*$Command = Get-WmiObject Win32_Process | select name,CommandLine*
function Get-Processplus {
[CmdletBinding(DefaultParameterSetName = 'Default')]
param (
[Parameter(ParameterSetName='ProcessName',Position = 0)]
[string[]]
$Name,*[Parameter(ParameterSetName='CommandLine',Position = 0)]
[string[]]
$Command,*
[Parameter(ParameterSetName='PID',Position = 0)]
[int[]]
$Id
)
# Check which parameter set is in use and get our processes
switch ($PSCmdlet.ParameterSetName) {
'ProcessName' {
$AllProcesses = Get-Process -Name $Name
break
}
*'CommandLine' {
$AllProcesses = Get-Process -Name $Command
break
}*
'PID' {
$AllProcesses = Get-Process -Id $Id
break
}
default { $AllProcesses = Get-Process }
}
foreach ($Process in $AllProcesses) {
# Retrieve TCP and UDP Connection information for the current process (if any)
$UDPConnections = Get-NetUDPEndpoint -OwningProcess $Process.Id -ErrorAction Ignore |
Select-Object LocalAddress,LocalPort
$TCPConnections = Get-NetTCPConnection -OwningProcess $Process.Id -State Listen -ErrorAction Ignore |
Select-Object LocalAddress,LocalPort
$TCPPorts = $TCPConnections.LocalPort | Where-Object { $null -ne $_} | Select-Object -Unique
$UDPPorts = $UDPConnections.LocalPort | Where-Object { $null -ne $_} | Select-Object -Unique
$TCPAddresses = $TCPConnections.LocalAddress | Select-Object -Unique
$UDPAddresses = $UDPConnections.LocalAddress | Select-Object -Unique
# Collect and output all information about the current process
[PSCustomObject] @{
'ProcessName' = $Process.ProcessName
'Id' = $Process.Id
'Description' = $Process.Description
'Path' = $Process.Path
*'CommandLine' = $Process.Command*
'cpu usage (s)' = $Process.cpu
'TCP Addresses' = $TCPAddresses
'TCP Ports' = $TCPPorts
'UDP Addresses' = $UDPAddresses
'UDP Ports' = $UDPPorts
}
}
}
解决方法
您需要将 Get-WMIObject
输出与 Get-Process
输出匹配。在您的情况下,只需替换此行:
'CommandLine' = $Process.Command
有了这个:
# Query WMI for process command line
'CommandLine' = Get-WmiObject -Query "
SELECT CommandLine from Win32_Process WHERE ProcessID = $($Process.ID)" |
# Select only the commandline property so we can display it
Select -ExpandProperty CommandLine
我的输出看起来像这样:
Get-ProcessPlus -Name notepad
ProcessName : notepad
Id : 10568
Description : Notepad
Path : C:\WINDOWS\system32\notepad.exe
CommandLine : "C:\WINDOWS\system32\notepad.exe" C:\temp\test.txt
CPU usage (s) : 0.390625
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。