Powershell: Difference between revisions

From Piszczynski
piszczynski>Aleks
piszczynski>Aleks
Line 5: Line 5:


<span style='color:#666616; '>Start-Process</span> <span style='color:#0000e6; '>powershell</span> <span style='color:#074726; '>-Verb</span> <span style='color:#0000e6; '>runAs</span>
<span style='color:#666616; '>Start-Process</span> <span style='color:#0000e6; '>powershell</span> <span style='color:#074726; '>-Verb</span> <span style='color:#0000e6; '>runAs</span>
 
----
Delete contents of folder
Delete contents of folder
* Get-ChildItem C:\LocationOfFolder\Folder -Recurse | ForEach { Remove-Item $_.FullName -Force -Recurse }
* Get-ChildItem C:\LocationOfFolder\Folder -Recurse | ForEach { Remove-Item $_.FullName -Force -Recurse }
 
----
Change to environment locations:
Change to environment locations:


Line 14: Line 14:


<span style='color:#005fd2; '>cd</span> <span style='color:#797997; '>$</span><span style='color:#007997; '>Env:</span><span style='color:#797997; '>userprofile</span>
<span style='color:#005fd2; '>cd</span> <span style='color:#797997; '>$</span><span style='color:#007997; '>Env:</span><span style='color:#797997; '>userprofile</span>
 
----
Show all environment vairables:
Show all environment vairables:


*dir env:
*dir env:


 
----
Show path to PS modules:
Show path to PS modules:
<pre>
<pre>
$env:PSProfilepath
$env:PSProfilepath
</pre>
</pre>
 
----
Restart computer remotely:
Restart computer remotely:


<span style='color:#666616; '>restart-computer</span> <span style='color:#074726; '>-Computername</span> <span style='color:#0000e6; '>[hostname]</span> <span style='color:#074726; '>-Credential</span> <span style='color:#0000e6; '>[domain\username]</span> <span style='color:#074726; '>-force</span>
<span style='color:#666616; '>restart-computer</span> <span style='color:#074726; '>-Computername</span> <span style='color:#0000e6; '>[hostname]</span> <span style='color:#074726; '>-Credential</span> <span style='color:#0000e6; '>[domain\username]</span> <span style='color:#074726; '>-force</span>
 
----
Send a message to a user on a remote host:
Send a message to a user on a remote host:
<pre>
<pre>
msg /server:<server name> /v <user name> <message>
msg /server:<server name> /v <user name> <message>
</pre>
</pre>
----
Connect to remote powershell session:
Connect to remote powershell session:


Line 46: Line 47:


<span style='color:#666616; '>Remove-PSSession</span> <span style='color:#797997; '>$sess</span>
<span style='color:#666616; '>Remove-PSSession</span> <span style='color:#797997; '>$sess</span>
 
----


Get services running on computer and display in a pauseable list:
Get services running on computer and display in a pauseable list:
Line 54: Line 55:
<span style='color:#666616; '>gsv</span> <span style='color:#bb7977; font-weight:bold; '>|</span> <span style='color:#666616; '>where</span> <span style='color:#808030; '>{</span><span style='color:#007997; '>$_</span><span style='color:#44aadd; '>.</span><span style='color:#005fd2; '>Status</span> <span style='color:#44aadd; '>-eq</span> <span style='color:#800000; '>"</span><span style='color:#0000e6; '>running</span><span style='color:#800000; '>"</span><span style='color:#808030; '>}</span> <span style='color:#bb7977; font-weight:bold; '>|</span> <span style='color:#005fd2; '>more</span>
<span style='color:#666616; '>gsv</span> <span style='color:#bb7977; font-weight:bold; '>|</span> <span style='color:#666616; '>where</span> <span style='color:#808030; '>{</span><span style='color:#007997; '>$_</span><span style='color:#44aadd; '>.</span><span style='color:#005fd2; '>Status</span> <span style='color:#44aadd; '>-eq</span> <span style='color:#800000; '>"</span><span style='color:#0000e6; '>running</span><span style='color:#800000; '>"</span><span style='color:#808030; '>}</span> <span style='color:#bb7977; font-weight:bold; '>|</span> <span style='color:#005fd2; '>more</span>


 
----
Output Command History to text file:
Output Command History to text file:
<pre>
<pre>
Line 60: Line 61:
</pre>
</pre>


 
----
Script to ping IP address and log time and status of ping:
Script to ping IP address and log time and status of ping:


https://github.com/AleksPish/NetworkPingTest/blob/master/NetworkDownTest.ps1
https://github.com/AleksPish/NetworkPingTest/blob/master/NetworkDownTest.ps1
 
----
Download file from internet:
Download file from internet:
* Invoke-WebRequest <URL> | out-file <File Pathway>
* Invoke-WebRequest <URL> | out-file <File Pathway>
Line 72: Line 73:
**$client.DownloadFile($url, $path)
**$client.DownloadFile($url, $path)
*(new-object System.Net.WebClient).DownloadFile( '$url, $path)
*(new-object System.Net.WebClient).DownloadFile( '$url, $path)
 
----
Add Exclusions to security check from downloaded programs:
Add Exclusions to security check from downloaded programs:
<pre>
<pre>
add-mppreference -exclusionpath "<full filepath - eg C:\users\downloads>"
add-mppreference -exclusionpath "<full filepath - eg C:\users\downloads>"
</pre>
</pre>
 
----
Get members of ad group:
Get members of ad group:
<pre>
<pre>
get-adgroupmember -identity "<name of adgroup>" | select-object name
get-adgroupmember -identity "<name of adgroup>" | select-object name
</pre>
</pre>
 
----
Get Computer / Server Uptime - last boot time
Get Computer / Server Uptime - last boot time
* (get-date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
* (get-date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
* Get-ComputerInfo | Select-Object OsUptime    - can also use OsLastBootUpTime to work it out
* Get-ComputerInfo | Select-Object OsUptime    - can also use OsLastBootUpTime to work it out
 
----
Get detailed information on server / computer operating system
Get detailed information on server / computer operating system
* Get-CimInstance Win32_OperatingSystem | FL *
* Get-CimInstance Win32_OperatingSystem | FL *
 
----
Add exception to windows defender for downloads in default user location:
Add exception to windows defender for downloads in default user location:
*add-mppreference -exclusionpath "C:\Users\*\Downloads\noActiveX-*.exe"
*add-mppreference -exclusionpath "C:\Users\*\Downloads\noActiveX-*.exe"
 
----
Get time between two dates:
Get time between two dates:
*New-TimeSpan -start <date> -end <date>
*New-TimeSpan -start <date> -end <date>

Revision as of 11:26, 23 July 2021

Handy Powershell

Open another powershell window as admin:

Start-Process powershell -Verb runAs


Delete contents of folder

  • Get-ChildItem C:\LocationOfFolder\Folder -Recurse | ForEach { Remove-Item $_.FullName -Force -Recurse }

Change to environment locations:

cd $Env:<vairable>

cd $Env:userprofile


Show all environment vairables:

  • dir env:

Show path to PS modules:

$env:PSProfilepath

Restart computer remotely:

restart-computer -Computername [hostname] -Credential [domain\username] -force


Send a message to a user on a remote host:

msg /server:<server name> /v <user name> <message>

Connect to remote powershell session:

$cred=Get-Credential

$sess = New-PSSession -Credential $cred -ComputerName <remotemachinename>

Enter-PSSession $sess

<Run commands in remote session>

Exit-PSSession

Remove-PSSession $sess


Get services running on computer and display in a pauseable list:

Get-service | Where-Object {$_.Status -eq "Stopped"} | More

gsv | where {$_.Status -eq "running"} | more


Output Command History to text file:

Get-History | ForEach-Object { $_.CommandLine } > $env.USERPROFILE\testoutput.txt

Script to ping IP address and log time and status of ping:

https://github.com/AleksPish/NetworkPingTest/blob/master/NetworkDownTest.ps1


Download file from internet:

  • Invoke-WebRequest <URL> | out-file <File Pathway>

Also can use Download method of WebClient

  • $client = New-Object System.Net.WebClient
    • $client.DownloadFile($url, $path)
  • (new-object System.Net.WebClient).DownloadFile( '$url, $path)

Add Exclusions to security check from downloaded programs:

add-mppreference -exclusionpath "<full filepath - eg C:\users\downloads>"

Get members of ad group:

get-adgroupmember -identity "<name of adgroup>" | select-object name

Get Computer / Server Uptime - last boot time

  • (get-date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
  • Get-ComputerInfo | Select-Object OsUptime - can also use OsLastBootUpTime to work it out

Get detailed information on server / computer operating system

  • Get-CimInstance Win32_OperatingSystem | FL *

Add exception to windows defender for downloads in default user location:

  • add-mppreference -exclusionpath "C:\Users\*\Downloads\noActiveX-*.exe"

Get time between two dates:

  • New-TimeSpan -start <date> -end <date>

Active Directory Powershell

Export details of users in a specific OU:

$OUpath = '<place OU path here distinguished name of ou in attribute editor>'
$ExportPath = '<place where to put output>'
Get-ADUser -Filter * -SearchBase $OUpath | Select-object DistinguishedName,Name,UserPrincipalName,sAMAccountName | Export-Csv -NoType $ExportPath

Get all groups a user is assigned to

  • Get-ADPrincipalGroupMembership username | select name

Change password expiry setting on ad accounts by OU Import-Module ActiveDirectory

  • Get-ADUser -Filter * -SearchBase "OU=TestOU,DC=TestDomain,DC=Local" | Set-ADUser -PasswordNeverExpires:$True

Search for adusers using powershell:

Can be used with various options: DistinguishedName, Enabled, GivenName, Name, ObjectClass, Object GUID, SamAccountName, SID, Surname, UserPrincipalName.

get-aduser -filter "name -eq '<name of user>'"

Powershell for Admin

Get powershell update

Get FSMO roles on which domain controllers at domain level:

Get-ADDomain | Select-Object InfrastructureMaster,PDCEmulator,RIDMaster | Format-List

Get FSMO roles on which domain controllers at forest level:

Get-ADForest | Select-Object DomainNamingMaster,SchemaMaster | Format-List

Installing packages in powershell

Can use chocolatey to get packages:

Set-ExecutionPolicy Unrestricted
iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex

For SSH connections:

Putty:

choco install putty

OpenSSH:

choco install openssh                # installs open ssh
refreshenv                           # reloads the environment variables
ssh remoteClient -i "MyKeyPair.pem"  # connects to remoteClient via ssh

poshSSH:

Install-Module Posh-SSH                                   # installs the posh-ssh module
Get-Command -Module Posh-SSH                              # shows all posh-ssh commandlets
New-SSHSession myclient -KeyFile "c:\data\MyKeyPair.pem"  # connect to my client with the give keyfile
Invoke-SSHCommandStream "ifconfig" -SessionId 0           # send ifconfig to the ssh session with id 0
Invoke-SSHCommand -SessionId 0 -Command "ifconfig"        # send ifconfig to the ssh session with id 0 
Invoke-SSHCommand -SessionId 0 -Command "logout"          # send logout to the ssh session with id 0
Remove-SSHSession 0                                       # removes and closes the ssh session

For firefox:

choco install firefox -y


Powershell Alias

gsv Get-Service

spsv Stop-Service

sasv Start-Service

Powershell for Services and Processes

Get all properties of a service and display specific properties of the service:

  • get-service | get-member
  • get-service wuauserv | select Displayname,Status,ServiceName,Can*

Display list of only running services:

  • Get-Service | Where-Object {$_.Status -EQ "Running"}

Remotely Check Service:

  • get-service wuauserv -ComputerName remotePC1

Get Service PID to kill process:

  • $ServicePID = (get-wmiobject win32_service | where { $_.name -eq 'service name'}).processID
  • Stop-Process $ServicePID -Force

Get top 10 processes by memory usage

  • Get-Process | Select-Object name,workingset64 | Sort-Object -Property workingset64 -Descending | Select-Object -First 10

Get User Process with an active GUI (no background processes will be displayed:

  • Get-Process | Where-Object {$_.mainWindowTitle}