Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

With-Credentials #15

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 60 additions & 18 deletions Get-NetworkStatistics.ps1
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function Get-NetworkStatistics {
function Get-NetworkStatistics {
<#
.SYNOPSIS
Display current TCP/IP connections for local or remote system
Expand All @@ -8,8 +8,11 @@

.DESCRIPTION
Display current TCP/IP connections for local or remote system. Includes the process ID (PID) and process name for each connection.
If the port is not yet established, the port number is shown as an asterisk (*).

If the port is not yet established, the port number is shown as an asterisk (*).

.PARAMETER Credential
Pass a set of PSCredentials to the function for accessing remote systems. Optional.

.PARAMETER ProcessName
Gets connections by the name of the process. The default value is '*'.

Expand Down Expand Up @@ -84,7 +87,7 @@
System.Management.Automation.PSObject

.NOTES
Author: Shay Levy, code butchered by Cookie Monster
Author: Shay Levy, code butchered by Cookie Monster. Further modified by David Garland
Shay's Blog: http://PowerShay.com
Cookie Monster's Blog: http://ramblingcookiemonster.github.io/

Expand All @@ -94,7 +97,7 @@
[OutputType('System.Management.Automation.PSObject')]
[CmdletBinding()]
param(
[Parameter(Position=0)]
[System.String]$ProcessName='*',

Expand Down Expand Up @@ -122,12 +125,19 @@
[System.String]$TempFile = "C:\netstat.txt",

[validateset('*','IPv4','IPv6')]
[string]$AddressFamily = '*'
[string]$AddressFamily = '*',

[Parameter()]
[ValidateNotNull()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential = [System.Management.Automation.PSCredential]::Empty

)

begin{
#Define properties
$properties = 'ComputerName','Protocol','LocalAddress','LocalPort','RemoteAddress','RemotePort','State','ProcessName','PID'
$properties = 'ComputerName','Protocol','LocalAddress','LocalPort','RemoteAddress','RemotePort','State','ProcessName','PID','Credential'

#store hostnames in array for quick lookup
$dnsCache = @{}
Expand All @@ -141,7 +151,11 @@
#Collect processes
if($ShowProcessNames){
Try {
$processes = Get-Process -ComputerName $Computer -ErrorAction stop | select name, id
if ($Credential -ne [System.Management.Automation.PSCredential]::Empty) {
$processes = Get-WmiObject -Class Win32_Process -ComputerName $Computer -Credential $Credential -ErrorAction stop | select name, @{n="Id";e={$_.processid}}
} else {
$processes = Get-Process -ComputerName $Computer -ErrorAction stop | select name, id
}
}
Catch {
Write-warning "Could not run Get-Process -computername $Computer. Verify permissions and connectivity. Defaulting to no ShowProcessNames"
Expand All @@ -153,22 +167,22 @@
if($Computer -ne $env:COMPUTERNAME){

#define command
[string]$cmd = "cmd /c c:\windows\system32\netstat.exe -ano >> $tempFile"
[string]$cmd = "cmd /c netstat.exe -ano >> $tempFile"

#define remote file path - computername, drive, folder path
$remoteTempFile = "\\{0}\{1}`${2}" -f "$Computer", (split-path $tempFile -qualifier).TrimEnd(":"), (Split-Path $tempFile -noqualifier)

#delete previous results
Try{
$null = Invoke-WmiMethod -class Win32_process -name Create -ArgumentList "cmd /c del $tempFile" -ComputerName $Computer -ErrorAction stop
$null = Invoke-WmiMethod -class Win32_process -name Create -ArgumentList "cmd /c del $tempFile" -ComputerName $Computer -Credential $Credential -ErrorAction stop
}
Catch{
Write-Warning "Could not invoke create win32_process on $Computer to delete $tempfile"
}

#run command
Try{
$processID = (Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $cmd -ComputerName $Computer -ErrorAction stop).processid
$processID = (Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $cmd -ComputerName $Computer -Credential $Credential -ErrorAction stop).processid
}
Catch{
#If we didn't run netstat, break everything off
Expand All @@ -181,7 +195,11 @@
#This while should return true until the process completes
$(
try{
get-process -id $processid -computername $Computer -ErrorAction Stop
if ($Credential -ne [System.Management.Automation.PSCredential]::Empty) {
get-process -id $processid -computername $Computer -Credential $Credential -ErrorAction Stop
} else {
get-process -id $processid -computername $Computer -ErrorAction Stop
}
}
catch{
$FALSE
Expand All @@ -190,9 +208,33 @@
) {
start-sleep -seconds 2
}

start-sleep -seconds 10

#gather results
if(test-path $remoteTempFile){
if ($Credential -ne [System.Management.Automation.PSCredential]::Empty) {

$networkCred = $Credential.GetNetworkCredential()
net use \\$Computer\c$ $($networkCred.Password) /User:$($networkCred.domain)\$($networkCred.UserName) /y 2>&1>null
$quiet = New-PSDrive -Name P -PSProvider FileSystem -Root \\$Computer\c$ -Scope Script

$path = "P:\netstat.txt"

Try {
$results = Get-Content $path | Select-String -Pattern '\s+(TCP|UDP)'
}
Catch {
Throw "Count not get content from remote computer for results"
Break
}

Remove-Item -path $path -force

Remove-PSDrive -Name P

net use \\$Computer\c$ /delete /y 2>&1>null

} elseif (test-path $remoteTempFile){

Try {
$results = Get-Content $remoteTempFile | Select-String -Pattern '\s+(TCP|UDP)'
Expand Down Expand Up @@ -291,9 +333,9 @@
}

#Display progress bar prior to getting process name or host name
Write-Progress -Activity "Resolving host and process names"`
-Status "Resolving process ID $procId with remote address $remoteAddress and local address $localAddress"`
-PercentComplete (( $count / $totalCount ) * 100)
#Write-Progress -Activity "Resolving host and process names"`
#-Status "Resolving process ID $procId with remote address $remoteAddress and local address $localAddress"`
#-PercentComplete (( $count / $totalCount ) * 100)

#If we are running showprocessnames, get the matching name
if($ShowProcessNames -or $PSBoundParameters.ContainsKey -eq 'ProcessName'){
Expand Down Expand Up @@ -377,4 +419,4 @@
}
}
}
}
}