【发布时间】:2017-04-20 04:55:57
【问题描述】:
对不起,如果这是一个基本问题,我是一名 PS 初学者......为什么当我将以下 Powershell 函数添加到 $Profile 时,它运行良好并将输出写入控制台,但在以下情况下不产生任何输出我将它作为 .ps1 运行? (当我作为脚本运行时,它似乎在运行,但没有返回任何输出或错误。
我的执行策略 = 不受限制,我以管理员身份运行。想法?
function Get-NetStats
{
$properties = 'Protocol','LocalAddress','LocalPort'
$properties += 'RemoteAddress','RemotePort','State','ProcessName','PID'
netstat -ano | Select-String -Pattern '\s+(TCP|UDP)' | ForEach-Object {
$item = $_.line.split(" ",[System.StringSplitOptions]::RemoveEmptyEntries)
if($item[1] -notmatch '^\[::')
{
if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
{
$localAddress = $la.IPAddressToString
$localPort = $item[1].split('\]:')[-1]
}
else
{
$localAddress = $item[1].split(':')[0]
$localPort = $item[1].split(':')[-1]
}
if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
{
$remoteAddress = $ra.IPAddressToString
$remotePort = $item[2].split('\]:')[-1]
}
else
{
$remoteAddress = $item[2].split(':')[0]
$remotePort = $item[2].split(':')[-1]
}
New-Object PSObject -Property @{
PID = $item[-1]
ProcessName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name
Protocol = $item[0]
LocalAddress = $localAddress
LocalPort = $localPort
RemoteAddress =$remoteAddress
RemotePort = $remotePort
State = if($item[0] -eq 'tcp') {$item[3]} else {$null}
} | Select-Object -Property $properties
}
}
}
【问题讨论】:
-
"我从不调用我的函数,所以它永远不会运行。为什么它不输出任何东西?"
-
是的;确切地。仔细阅读 TessellatingHeckler 的评论。
标签: powershell