get receiving bytes and sending bytes using netsh command in powershell - powershell

NetAdapter module is not installed. I have to get the traffic flow (receiving Bytes and sender Bytes) like Get-NetAdapterStatistics commmand using netsh command. is it possible? kindly help
i am not an admin to install new modules.
Thanks

Per the comments, this is not a great question (you really should attempt to write some code first) but I have some suggestions anyway. You can actually install modules without being an admin, just use:
Install-Module <modulename> -Scope CurrentUser
And it will go in to the Documents\WindowsPowerShell\Modules directory under your profile.
However if you want to try to get these values into a PowerShell object without having that cmdlet, you could use the old DOS command netstat /e and scrape the text result to turn it in to an object:
$NetStat = (& netstat /e) -split '\s+'
$Stats = New-Object -TypeName PSObject -Property #{
Sent = $NetStat[9]
Received = $NetStat[8]
}
$Stats
Returns:
Sent Received
---- --------
256063580 1179546715

Related

Can PowerShell interact with RDP prompts?

I'm currently writing a script to automate a number of checks, I have a number of clients which I want to automatically log into one of their servers or use an app hosted via RDweb.
Right now my script works fine, however, I'm only able to get to the point that it'll start to execute the RDP pointer, I'm wondering if there's a way to hit "connect":
The method I'm currently using to run this:
[System.Diagnostics.Process]::Start("c:\file\path\file.rdp")
Is there a better way to run the .RDP file which will also allow you to "Connect"? I've also attempted to tick the "don't ask me" again, the next day it'll still prompt me with this message.
A solution I've found to start an RDP session that seems to work quite good is the following:
function Connect-RDP {
param (
[Parameter(Mandatory=$true)]
$ComputerName,
[System.Management.Automation.Credential()]
$Credential
)
# take each computername and process it individually
$ComputerName | ForEach-Object {
# if the user has submitted a credential, store it
# safely using cmdkey.exe for the given connection
if ($PSBoundParameters.ContainsKey('Credential'))
{
# extract username and password from credential
$User = $Credential.UserName
$Password = $Credential.GetNetworkCredential().Password
# save information using cmdkey.exe
cmdkey.exe /generic:$_ /user:$User /pass:$Password
}
# initiate the RDP connection
# connection will automatically use cached credentials
# if there are no cached credentials, you will have to log on
# manually, so on first use, make sure you use -Credential to submit
# logon credential
mstsc.exe /v $_ /f
}
}
Then you call it with Connect-rdp -ComputerName myserver -Credential (Get-Credential ).
Maybe you can adjust your script to use this cmdlet instead of your file.rdp.
I found the solution here:
https://www.powershellmagazine.com/2014/04/18/automatic-remote-desktop-connection/
Another way you could try is this:
[void][System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
# Get the ID of the process
$WindowsHandle = Get-Process | Where-Object { $_.MainWindowTitle -Match 'Remote Desktop Connection' } | Select-Object -ExpandProperty Id
# Activate the window
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate($WindowsHandle) | Out-Null
# SendKey to connect
[System.Windows.Forms.SendKeys]::SendWait("%{c}")
%{c} stands for ALT+C
The modifier keys are:
Key | Code
-----------
SHIFT +
CTRL ^
ALT %

Powershell Get-EventLog from computers.txt and save data

I have some problems getting EventLog and save data. I am able to get my EventLogs but not logs from network computers.
Here is the code I am running:
$logFileName = "Application"
$path = $MyInvocation.MyCommand.Path +"\Output\"
$path = $PSScriptRoot+"\Output\"
new-item $path -ItemType directory
$array = ("System", "Security")
$file = $PSScriptRoot +"\computers.txt"
$users = ForEach ($machine in $(Get-Content $file)) {
$pathMachine = $path+$machine
new-item $pathMachine -ItemType directory
ForEach ($logFileName in $array){
# do not edit
$logFileName
$exportFileName = (get-date -f yyyyMMdd) + "_" + $logFileName + ".evt"
$logFile = Get-WmiObject Win32_NTEventlogFile -ComputerName $machine | Where-Object {$_.logfilename -eq $logFileName}
$logFile
$exportFileName
$pathMachine
$temp = $pathMachine + "\"+ $exportFileName
$temp
$fff = $logFile.BackupEventLog($temp)
}
}
This could e considered a duplicate of this.
Reading event log remotely with Get-EventLog in Powershell
# swapped from this command
get-eventlog -LogName System -computername <ServerName>
# to this
invoke-command {get-eventlog -LogName System} -ComputerName <ServerName>
Don't struggle with writing this from scratch. Well, unless it's a learning exercise. There are pre-built script for you to leverage as is and or tweak as needed.
Running commands on Remote host require using the Invoke cmdlet, and or an established PSRemoting session to that host.
Get Remote Event Logs With Powershell
Gather the remote event log information for one or more systems using wmi, alternate credentials, and multiple runspaces. Function supports custom timeout parameters in case of wmi problems and returns Event Log information for the specified number of past hours.
Download: Get-RemoteEventLogs.ps1
The script is too long (it's 100+ lines) to post here, but here in the Synopsis of it.
Function Get-RemoteEventLogs
{
<#
.SYNOPSIS
Retrieves event logs via WMI in multiple runspaces.
.DESCRIPTION
Retrieves event logs via WMI and, if needed, alternate credentials. This function utilizes multiple runspaces.
.PARAMETER ComputerName
Specifies the target computer or comptuers for data query.
.PARAMETER Hours
Gather event logs from the last number of hourse specified here.
.PARAMETER ThrottleLimit
Specifies the maximum number of systems to inventory simultaneously
.PARAMETER Timeout
Specifies the maximum time in second command can run in background before terminating this thread.
.PARAMETER ShowProgress
Show progress bar information
.EXAMPLE
PS > (Get-RemoteEventLogs).EventLogs
Description
-----------
Lists all of the event logs found on the localhost in the last 24 hours.
.NOTES
Author: Zachary Loeber
Site: http://www.the-little-things.net/
Requires: Powershell 2.0
Version History
1.0.0 - 08/28/2013
- Initial release
#>
Or this one.
PowerShell To Get Event Log of local or Remote Computers in .csv file
This script is handy when you want to extract the eventlog from remote or local machine. It has multiple filters which will help to filter the data. You can filter by logname,event type, source etc. This also have facility to get the data based on date range. You can change th
Download : eventLogFromRemoteSystem.ps1
Again, too big to post here because the length is like the other one.
I am working on some assumptions but maybe this will help.
When I Ran your Code I got
Get-Content : Cannot find path 'C:\computers.txt' because it does not exist.
I had to make the C:\computers.txt file, then I ran your code again and got this error.
Get-Content : Cannot find path 'C:\Output\computers.txt' because it does not exist.
I made that file in that location, then I ran your code again and I got the event log file. Maybe try creating these two missing files with a command like
Get-WmiObject Win32_NTEventlogFile -ComputerName $machine
mkdir C:\Output\$machine
$env:computername | Out-File -FilePath c:\Output\Computers.txt
You may also want to setup a Network share and output to that location so you can access the event logs from a single computer. Once the share is setup and the permissions just drop the unc path in.

View recent remote powershell connections

Is there an event log of some kind that is made when a remote pssession is initiated on a computer? I need to be able to see where a remote session has originated from.
Currently I am running
Get-EventLog -LogName "Windows powershell" -newest 100 | Format-List -Property * | where {$_.UserID -eq "username"}
But it is not filtering and/or showing remote connections.
We are here to help you with code issues. This is really not a code issue, but a understanding of how to set up and where correlate such detail. So, it's potentially a question for another forum.
Anyway, to get you close to what you are after, there are extra steps you need to employ to get such information. More on that in a bit.
Now, once you get this all setup and you write your script to pull / look at such info and you are having issues with that, then post that back here for folks to see what can be done
So, that leads us to here:
There are three general areas for logging available:
• Module Logging
• Script Block Logging
• PowerShell Transcription
If you have not done so, I would advise enabling on PS auditing and script logging for more insight into this use case and well as transcript logging (which can capture all commands / code executed on a host machine). If you set all this up properly, you fist look to the transcript log for details and well as the log name you reference in your post for other details.
Set this enterprise wide via GPO or DSC.
There is lot's of guidance on how to set this up.
For Example:
Audit PowerShell Usage using Transcription and Logging
Get-Command -Name '*transcript*'
CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Get-TRSTranscriptionJob 3.3.234.0 AWSPowerShell
Cmdlet Get-TRSTranscriptionJobList 3.3.234.0 AWSPowerShell
Cmdlet Start-Transcript 3.0.0.0 Microsoft.PowerShell.Host
Cmdlet Start-TRSTranscriptionJob 3.3.234.0 AWSPowerShell
Cmdlet Stop-Transcript 3.0.0.0 Microsoft.PowerShell.Host
https://learn.microsoft.com/en-us/powershell/wmf/5.0/audit_overview
Practical PowerShell Security: Enable Auditing and Logging with DSC
https://blogs.technet.microsoft.com/ashleymcglone/2017/03/29/practical-powershell-security-enable-auditing-and-logging-with-dsc
More New Stuff in PowerShell V5: Extra PowerShell Auditing
Get-Module Microsoft.* | Select Name, LogPipelineExecutionDetails
Get-Module Microsoft.* | ForEach { $_.LogPipelineExecutionDetails = $True }
(Import-Module ActiveDirectory).LogPipelineExecutionDetails = $True
Get-WinEvent -FilterHashtable #{LogName='Windows PowerShell';Id ='800'} -MaxEvents 1 | Select -Expand Message
https://learn-powershell.net/2014/08/26/more-new-stuff-in-powershell-v5-extra-powershell-auditing
Investigating PowerShell: Command and Script Logging
https://www.crowdstrike.com/blog/investigating-powershell-command-and-script-logging

Running Command as Administrator from a SYSTEM Process

So I need to clear a user's run dialog history which I can do perfectly fine with "reg delete HKEY_CURRENT_USER\Software\Windows etc..." from an elevated powershell window on the logged in user's machine, but what I'm looking to do is that same command but from a SYSTEM powershell process. I have already used psexec to create a powershell window which runs as SYSTEM, but because you can't just use HKEY_CURRENT_USER as SYSTEM with the same results, I am finding it quite difficult. If I could just run that command but as username\Administrator then I wouldn't have this problem.
Also to note, if I can somehow grab the username of the logged on user (from SYSTEM still) in one line in plain text (with no other output in sight), then I can store the username in a variable and convert that to an SID and use HKEY_USERS instead.
P.S. Don't ask why I'm running powershell as SYSTEM, I know what I'm doing :D
you can use get-process under the system context powershell and filter where explorer.exe process is running, get the account it is running under then use to convert to SID and go through the registry.
something like this assuming only 1 explorer.exe process is running which is the norm on windows client OS.
$proc = Get-CimInstance Win32_Process -Filter "name = 'explorer.exe'"
$owner = Invoke-CimMethod -InputObject $proc -MethodName GetOwner
$username = $owner.user
$username will contain the user, $owner will also contain domain and a few other things.
to convert to sid
$objUser = New-Object System.Security.Principal.NTAccount($owner.Domain, $owner.User)
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSID.Value

Decode powershell command to code

It is possible decode (or show what to do) command Powershell?
I try use command connect-msolservice, but i get exceptions:
.
So maybe if I get content command, i can configure system to this connection.
Yes, you can use ILSpy to decode powershell dll. Download ILSpy.
For find path .dll with your cmdlets, use powershell command:
Get-Command connect-msolservice | fl DLL,ImplementingType
Or you can use a native solution to view the Metadata of the builtin (or any other cmdlets)
$Metadata = New-Object System.Management.Automation.CommandMetaData (Get-Command Connect-MSOLService)
$Contents = [System.Management.Automation.ProxyCommand]::Create($Metadata)
credit to http://windowsitpro.com/blog/powershell-proxy-functions