piszczynski>Aleks |
|||
(38 intermediate revisions by 2 users not shown) | |||
Line 2: | Line 2: | ||
== Handy Powershell == | == Handy Powershell == | ||
Divert errors to a file: | |||
<syntaxhighlight lang="powershell"><command> 2>> C:\temp\filecontainingerrors.txt</syntaxhighlight> | |||
<syntaxhighlight lang="powershell">Get-childitem -recurse 2>> C:\temp\errors.txt</syntaxhighlight> | |||
---- | |||
Open another powershell window as admin: | Open another powershell window as admin: | ||
< | <syntaxhighlight lang="powershell">Start-Process powershell -Verb runAs</syntaxhighlight> | ||
---- | ---- | ||
Get location of exe running proces: | Get location of exe running proces: | ||
<syntaxhighlight lang="powershell">get-process <process name> | fl path</syntaxhighlight> | |||
---- | ---- | ||
Delete contents of folder | Delete contents of folder | ||
<syntaxhighlight lang="powershell"> Get-ChildItem C:\LocationOfFolder\Folder -Recurse | ForEach { Remove-Item $_.FullName -Force -Recurse }</syntaxhighlight> | |||
---- | ---- | ||
Change to environment locations: | Change to environment locations: | ||
< | <syntaxhighlight lang="powershell">cd $Env:<vairable></syntaxhighlight> | ||
< | <syntaxhighlight lang="powershell">cd $Env:userprofile</syntaxhighlight> | ||
---- | ---- | ||
Show all environment vairables: | Show all environment vairables: | ||
<syntaxhighlight lang="powershell">dir env:</syntaxhighlight> | |||
---- | ---- | ||
Line 28: | Line 32: | ||
</pre> | </pre> | ||
---- | ---- | ||
Restart computer remotely: | Restart computer remotely:<syntaxhighlight lang="powershell"> | ||
restart-computer -Computername [hostname] -Credential [domain\username] -force | |||
< | </syntaxhighlight> | ||
---- | ---- | ||
Send a message to a user on a remote host: | Send a message to a user on a remote host: | ||
Line 37: | Line 41: | ||
</pre> | </pre> | ||
---- | ---- | ||
Connect to remote powershell session: | ===Powershell Remoting=== | ||
Connect to remote powershell session:<syntaxhighlight lang="powershell"> | |||
$cred=Get-Credential | |||
$sess = New-PSSession -Credential $cred -ComputerName <remotemachinename> | |||
Enter-PSSession $sess | |||
< | <Run commands in remote session> | ||
Exit-PSSession | |||
Remove-PSSession $sess | |||
</syntaxhighlight> | |||
---- | |||
If you are getting an error when remoting like "WinRM cannot process the request." use Windows PowerShell to add each server to the Trusted Hosts list on your management computer: | |||
<syntaxhighlight lang="powershell">Set-Item WSMAN:\Localhost\Client\TrustedHosts -Value Server01 -Force</syntaxhighlight> | |||
Note: the trusted hosts list supports wildcards, like Server* | |||
To view your Trusted Hosts list: | |||
<syntaxhighlight lang="powershell">Get-Item WSMAN:\Localhost\Client\TrustedHosts</syntaxhighlight> | |||
< | To empty the list: | ||
<syntaxhighlight lang="powershell">Clear-Item WSMAN:\Localhost\Client\TrustedHost</syntaxhighlight> | |||
---- | |||
If errors show run the following command to check on the winrm service+config: | |||
<syntaxhighlight lang="powershell">winrm quickconfig</syntaxhighlight> | |||
---- | ---- | ||
===Services with Powershell=== | |||
Get services running on computer and display in a pauseable list: | Get services running on computer and display in a pauseable list:<syntaxhighlight lang="powershell"> | ||
Get-Service | Where-Object {$_.Status -eq "Stopped"} | More | |||
< | </syntaxhighlight><syntaxhighlight lang="powershell"> | ||
gsv | where {$_.Status -eq "running"} | more | |||
</syntaxhighlight> | |||
---- | ---- | ||
Line 67: | Line 84: | ||
Pipe to "out-string -width 500" to display in a sting of set number of characters: | Pipe to "out-string -width 500" to display in a sting of set number of characters: | ||
<syntaxhighlight lang="powershell"><command> | out-string -width 500</syntaxhighlight> | |||
In the case of an array change the vairable $FormatEnumerationLimit to -1 | In the case of an array change the vairable $FormatEnumerationLimit to -1 | ||
<syntaxhighlight lang="powershell">$FormatEnumerationLimit=-1</syntaxhighlight> | |||
---- | ---- | ||
Script to ping IP address and log time and status of ping: | Script to ping IP address and log time and status of ping: | ||
Line 77: | Line 94: | ||
---- | ---- | ||
Download file from internet: | Download file from internet: | ||
<syntaxhighlight lang="powershell"> Invoke-WebRequest <URL> | out-file <File Pathway></syntaxhighlight> | |||
Also can use Download method of WebClient | Also can use Download method of WebClient | ||
<syntaxhighlight lang="powershell" line>$client = New-Object System.Net.WebClient | |||
$client.DownloadFile($url, $path) | |||
(new-object System.Net.WebClient).DownloadFile( '$url, $path)</syntaxhighlight> | |||
---- | ---- | ||
Get public IP address of device: | Get public IP address of device: | ||
<syntaxhighlight lang="powershell">(Invoke-RestMethod ipinfo.io/json).ip</syntaxhighlight> | |||
---- | ---- | ||
Add Exclusions to security check from downloaded programs: | Add Exclusions to security check from downloaded programs: | ||
Line 98: | Line 115: | ||
---- | ---- | ||
Get Computer / Server Uptime - last boot time | Get Computer / Server Uptime - last boot time | ||
<syntaxhighlight lang="powershell>(get-date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime</syntaxhighlight> | |||
<syntaxhighlight lang="powershell"> Get-ComputerInfo | Select-Object OsUptime - can also use OsLastBootUpTime to work it out</syntaxhighlight> | |||
---- | ---- | ||
Get detailed information on server / computer operating system | Get detailed information on server / computer operating system | ||
<syntaxhighlight lang="powershell"> Get-CimInstance Win32_OperatingSystem | FL *</syntaxhighlight> | |||
---- | ---- | ||
Add exception to windows defender for downloads in default user location: | Add exception to windows defender for downloads in default user location: | ||
<syntaxhighlight lang="powershell">add-mppreference -exclusionpath "C:\Users\*\Downloads\noActiveX-*.exe"</syntaxhighlight> | |||
---- | ---- | ||
Get time between two dates: | Get time between two dates: | ||
<syntaxhighlight lang="powershell">New-TimeSpan -start <date> -end <date></syntaxhighlight> | |||
---- | ---- | ||
==Powershell Modules and comms errors== | |||
Install PS module | Install PS module | ||
<syntaxhighlight lang="powershell">Install-Module <name of module></syntaxhighlight> | |||
If there is an error the issue may be with TLS - run the following command first: | If there is an error the issue may be with TLS - run the following command first: | ||
<syntaxhighlight lang="powershell">[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12</syntaxhighlight> | |||
---- | ---- | ||
Resolve TLS problems for good by updating PowershellGet: | |||
<syntaxhighlight lang="powershell">Install-PackageProvider Nuget -force -Verbose</syntaxhighlight> | |||
<syntaxhighlight lang="powershell">Install-Module -Name PowershellGet -Force -Verbose</syntaxhighlight> | |||
== File Admin Powershell == | == File Admin Powershell == | ||
List | List folders<syntaxhighlight lang="powershell>Get-childitem</syntaxhighlight> | ||
Move all files of a specified extension from the current directory to another directory, move | Move all files of a specified extension from the current directory to another directory, move recursively<syntaxhighlight lang="powershell>Move-Item -Path .\*.txt -Destination <path></syntaxhighlight> | ||
<syntaxhighlight lang="powershell>Get-ChildItem -Path ".\*.txt" -Recurse | Move-Item -Destination "C:\TextFiles"</syntaxhighlight> | |||
Move registry keys and values to another | Move registry keys and values to another key<syntaxhighlight lang="powershell>Move-Item "HKLM:\software\mycompany\*" "HKLM:\software\mynewcompany"</syntaxhighlight></syntaxhighlight> | ||
Display errors that were seen when accessing files:<syntaxhighlight lang="powershell>$Error | ForEach-Object { Write-Host $_.TargetObject }</syntaxhighlight> | |||
== Active Directory Powershell == | == Active Directory Powershell == | ||
Export details of users in a specific OU: | Export details of users in a specific OU:<syntaxhighlight lang="powershell" line> | ||
< | |||
$OUpath = '<place OU path here distinguished name of ou in attribute editor>' | $OUpath = '<place OU path here distinguished name of ou in attribute editor>' | ||
$ExportPath = '<place where to put output>' | $ExportPath = '<place where to put output>' | ||
Get-ADUser -Filter * -SearchBase $OUpath | Select-object DistinguishedName,Name,UserPrincipalName,sAMAccountName | Export-Csv -NoType $ExportPath | Get-ADUser -Filter * -SearchBase $OUpath | Select-object DistinguishedName,Name,UserPrincipalName,sAMAccountName | Export-Csv -NoType $ExportPath | ||
</ | </syntaxhighlight> | ||
---- | ---- | ||
Get all groups a user is assigned to | Get all groups a user is assigned to | ||
<syntaxhighlight lang="powershell">Get-ADPrincipalGroupMembership username | select name</syntaxhighlight> | |||
---- | |||
Get group: | |||
<syntaxhighlight lang="powershell">Get-ADGroup -Identity <groupname></syntaxhighlight> | |||
---- | |||
Get members of group: | |||
<syntaxhighlight lang="powershell">Get-ADGroupMember -identity <groupname></syntaxhighlight> | |||
---- | ---- | ||
Change password expiry setting on ad accounts by OU | Change password expiry setting on ad accounts by OU | ||
Import-Module ActiveDirectory | Import-Module ActiveDirectory | ||
<syntaxhighlight lang="powershell">Get-ADUser -Filter * -SearchBase "OU=TestOU,DC=TestDomain,DC=Local" | Set-ADUser -PasswordNeverExpires:$True</syntaxhighlight> | |||
---- | ---- | ||
Search for adusers using powershell: | Search for adusers using powershell: | ||
Line 150: | Line 177: | ||
Can be used with various options: DistinguishedName, Enabled, GivenName, Name, ObjectClass, Object GUID, SamAccountName, SID, Surname, UserPrincipalName. | 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>'" | <syntaxhighlight lang="powershell">get-aduser -filter "name -eq '<name of user>'"</syntaxhighlight> | ||
---- | ---- | ||
Unlock user account: | Unlock user account: | ||
<syntaxhighlight lang="powershell">Get-ADuser -identity <username> | unlock-ADaccount</syntaxhighlight> | |||
Check for lock status: | Check for lock status: | ||
<syntaxhighlight lang="powershell">Get-ADuser -Identity <username> -properties Lockedout</syntaxhighlight> | |||
===Local Accounts commands=== | |||
Use for managing local accounts: | |||
<syntaxhighlight lang="powershell">New-localUser -name "<name>"</syntaxhighlight> | |||
Change details of local user | |||
<syntaxhighlight lang="powershell">Set-localuser</syntaxhighlight> | |||
Change password: | |||
<syntaxhighlight lang="powershell">$Password = Read-Host -AsSecureString</syntaxhighlight> | |||
<syntaxhighlight lang="powershell">$UserAccount = Get-LocalUser -Name "<name>"</syntaxhighlight> | |||
<syntaxhighlight lang="powershell">$UserAccount | Set-LocalUser -Password $Password</syntaxhighlight> | |||
Add to group: | |||
<syntaxhighlight lang="powershell">Add-localgroupmember -group "<Groupname>" -member "<username>"</syntaxhighlight> | |||
== Powershell for Admin == | == Powershell for Admin == | ||
Get powershell update | Get powershell update | ||
<syntaxhighlight lang="powershell">iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"</syntaxhighlight> | |||
Get FSMO roles on which domain controllers at domain level: | Get FSMO roles on which domain controllers at domain level: | ||
Line 172: | Line 216: | ||
Get-ADForest | Select-Object DomainNamingMaster,SchemaMaster | Format-List | Get-ADForest | Select-Object DomainNamingMaster,SchemaMaster | Format-List | ||
</pre> | </pre> | ||
Get all current logged in sessions: | |||
<syntaxhighlight lang="powershell">(Get-CimInstance Win32_LoggedOnUser)</syntaxhighlight> | |||
== Installing packages in powershell == | == Installing packages in powershell == | ||
Use winget to install packages:<syntaxhighlight lang="powershell"> | |||
winget install <package name> | |||
</syntaxhighlight>You may need to specify the source:<syntaxhighlight lang="powershell"> | |||
winget install <package name> --source winget | |||
</syntaxhighlight>Upgrade/update packages with winget:<syntaxhighlight lang="powershell"> | |||
winget upgrade --all | |||
</syntaxhighlight>Chocolatey is now pretty much depreciated with the introduction of winget - install with MS store | |||
Can use chocolatey to get packages: | Can use chocolatey to get packages: | ||
Line 209: | Line 265: | ||
</pre> | </pre> | ||
==Issue with psrepository== | |||
try to fix psrepository: | |||
<syntaxhighlight lang="powershell">Register-PSRepository -Default</syntaxhighlight> | |||
If this fails use the following: | |||
Install the PSRepository using the following settings: | |||
<pre> | |||
$Repository = @{ | |||
Name = 'PSGallery' | |||
SourceLocation = 'https://www.powershellgallery.com/api/v2/' | |||
PublishLocation = 'https://www.powershellgallery.com/api/v2/package/' | |||
ScriptSourceLocation = 'https://www.powershellgallery.com/api/v2/items/psscript' | |||
ScriptPublishLocation = 'https://www.powershellgallery.com/api/v2/package/' | |||
InstallationPolicy = 'Untrusted' | |||
} | |||
Register-PSRepository @Repository | |||
</pre> | |||
== Powershell Alias == | == Powershell Alias == | ||
Line 222: | Line 297: | ||
Get all properties of a service and display specific properties of the service: | Get all properties of a service and display specific properties of the service: | ||
<syntaxhighlight lang="powershell">get-service | get-member</syntaxhighlight> | |||
<syntaxhighlight lang="powershell">get-service wuauserv | select Displayname,Status,ServiceName,Can*</syntaxhighlight> | |||
Display list of only running services: | Display list of only running services: | ||
<syntaxhighlight lang="powershell">Get-Service | Where-Object {$_.Status -EQ "Running"}</syntaxhighlight> | |||
Remotely Check Service: | Remotely Check Service: | ||
<syntaxhighlight lang="powershell">get-service wuauserv -ComputerName remotePC1</syntaxhighlight> | |||
Get Service PID to kill process: | Get Service PID to kill process: | ||
<syntaxhighlight lang="powershell">$ServicePID = (get-wmiobject win32_service | where { $_.name -eq 'service name'}).processID </syntaxhighlight> | |||
<syntaxhighlight lang="powershell">Stop-Process $ServicePID -Force</syntaxhighlight> | |||
Get top 10 processes by memory usage | Get top 10 processes by memory usage | ||
<syntaxhighlight lang="powershell">Get-Process | Select-Object name,workingset64 | Sort-Object -Property workingset64 -Descending | Select-Object </syntaxhighlight>-First 10 | |||
Get User Process with an active GUI (no background processes will be displayed: | Get User Process with an active GUI (no background processes will be displayed: | ||
<syntaxhighlight lang="powershell">Get-Process | Where-Object {$_.mainWindowTitle}</syntaxhighlight> | |||
== Encrypt Passwords for use in Powershell scripts - scheduled tasks == | == Encrypt Passwords for use in Powershell scripts - scheduled tasks == | ||
=== Use Export-Clixml === | |||
Easiest way is to export the user credentials as an xml object using export-clixml then import with import-clixml: <syntaxhighlight lang="powershell" line="1"> | |||
$credential = Get-Credential | |||
$credential | Export-Clixml <file path to export file to> | |||
</syntaxhighlight>Then import the user credentials from the exported file (the credentials are stored encrypted in the xml file):<syntaxhighlight lang="powershell"> | |||
$credential = Import-Clixml <path to file to import> | |||
</syntaxhighlight> | |||
===Use convertfrom/to-securestring method=== | |||
Use the convertfrom-securestring command to take a secure string (password) then store as a file eg: | Use the convertfrom-securestring command to take a secure string (password) then store as a file eg: | ||
<syntaxhighlight lang="powershell">$SecurePassword = Read-host -AsSecureString | ConvertFrom-SecureString</syntaxhighlight> | |||
<syntaxhighlight lang="powershell">$SecurePassword | Out-File -FilePath "C:\Encrypted.key"</syntaxhighlight> | |||
To use the the passwords in a script use the get-content: | To use the the passwords in a script use the get-content: | ||
<syntaxhighlight lang="powershell">$username = "Administrator"</syntaxhighlight> | |||
<syntaxhighlight lang="powershell">$password = Get-Content "C:\Encrypted.key" | ConvertTo-SecureString</syntaxhighlight> | |||
<syntaxhighlight lang="powershell">$credential = New-Object System.Management.Automation.PsCredential($username,$password)</syntaxhighlight> | |||
If you want to encrypt the username and password you can do the following: | If you want to encrypt the username and password you can do the following: | ||
<syntaxhighlight lang="powershell">$securecred = Get-Credential</syntaxhighlight> | |||
<syntaxhighlight lang="powershell">$securecred.UserName | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | set-content </syntaxhighlight>"C:\Username.key" | |||
<syntaxhighlight lang="powershell">$securecred.Password | ConvertFrom-SecureString | set-content "C:\Password.key"</syntaxhighlight> | |||
They are stored in separate files | They are stored in separate files | ||
If you want to get the password back as plain text you can use the following:<syntaxhighlight lang="powershell"> | |||
$password = Get-Content "C:\Encrypted.key" | ConvertTo-SecureString | |||
$plainpassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)) | |||
</syntaxhighlight> | |||
== Script Writing Info == | == Script Writing Info == | ||
Find out what escape character to use for special characters: | Find out what escape character to use for special characters: | ||
<syntaxhighlight lang="powershell">[Regex]::Escape("<special character>")</syntaxhighlight> |
Latest revision as of 16:22, 25 January 2024
Handy Powershell
Divert errors to a file:
<command> 2>> C:\temp\filecontainingerrors.txt
Get-childitem -recurse 2>> C:\temp\errors.txt
Open another powershell window as admin:
Start-Process powershell -Verb runAs
Get location of exe running proces:
get-process <process name> | fl path
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>
Powershell Remoting
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
If you are getting an error when remoting like "WinRM cannot process the request." use Windows PowerShell to add each server to the Trusted Hosts list on your management computer:
Set-Item WSMAN:\Localhost\Client\TrustedHosts -Value Server01 -Force
Note: the trusted hosts list supports wildcards, like Server*
To view your Trusted Hosts list:
Get-Item WSMAN:\Localhost\Client\TrustedHosts
To empty the list:
Clear-Item WSMAN:\Localhost\Client\TrustedHost
If errors show run the following command to check on the winrm service+config:
winrm quickconfig
Services with Powershell
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
Get Powershell to display all output in the case that output is displayed truncated:
Pipe to "out-string -width 500" to display in a sting of set number of characters:
<command> | out-string -width 500
In the case of an array change the vairable $FormatEnumerationLimit to -1
$FormatEnumerationLimit=-1
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)
Get public IP address of device:
(Invoke-RestMethod ipinfo.io/json).ip
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>
Powershell Modules and comms errors
Install PS module
Install-Module <name of module>
If there is an error the issue may be with TLS - run the following command first:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Resolve TLS problems for good by updating PowershellGet:
Install-PackageProvider Nuget -force -Verbose
Install-Module -Name PowershellGet -Force -Verbose
File Admin Powershell
List folders
Get-childitem
Move all files of a specified extension from the current directory to another directory, move recursively
Move-Item -Path .\*.txt -Destination <path>
Get-ChildItem -Path ".\*.txt" -Recurse | Move-Item -Destination "C:\TextFiles"
Move registry keys and values to another key
Move-Item "HKLM:\software\mycompany\*" "HKLM:\software\mynewcompany"
</syntaxhighlight> Display errors that were seen when accessing files:
$Error | ForEach-Object { Write-Host $_.TargetObject }
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
Get group:
Get-ADGroup -Identity <groupname>
Get members of group:
Get-ADGroupMember -identity <groupname>
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>'"
Unlock user account:
Get-ADuser -identity <username> | unlock-ADaccount
Check for lock status:
Get-ADuser -Identity <username> -properties Lockedout
Local Accounts commands
Use for managing local accounts:
New-localUser -name "<name>"
Change details of local user
Set-localuser
Change password:
$Password = Read-Host -AsSecureString
$UserAccount = Get-LocalUser -Name "<name>"
$UserAccount | Set-LocalUser -Password $Password
Add to group:
Add-localgroupmember -group "<Groupname>" -member "<username>"
Powershell for Admin
Get powershell update
iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"
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
Get all current logged in sessions:
(Get-CimInstance Win32_LoggedOnUser)
Installing packages in powershell
Use winget to install packages:
winget install <package name>
You may need to specify the source:
winget install <package name> --source winget
Upgrade/update packages with winget:
winget upgrade --all
Chocolatey is now pretty much depreciated with the introduction of winget - install with MS store
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
Issue with psrepository
try to fix psrepository:
Register-PSRepository -Default
If this fails use the following:
Install the PSRepository using the following settings:
$Repository = @{ Name = 'PSGallery' SourceLocation = 'https://www.powershellgallery.com/api/v2/' PublishLocation = 'https://www.powershellgallery.com/api/v2/package/' ScriptSourceLocation = 'https://www.powershellgallery.com/api/v2/items/psscript' ScriptPublishLocation = 'https://www.powershellgallery.com/api/v2/package/' InstallationPolicy = 'Untrusted' } Register-PSRepository @Repository
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}
Encrypt Passwords for use in Powershell scripts - scheduled tasks
Use Export-Clixml
Easiest way is to export the user credentials as an xml object using export-clixml then import with import-clixml:
$credential = Get-Credential
$credential | Export-Clixml <file path to export file to>
Then import the user credentials from the exported file (the credentials are stored encrypted in the xml file):
$credential = Import-Clixml <path to file to import>
Use convertfrom/to-securestring method
Use the convertfrom-securestring command to take a secure string (password) then store as a file eg:
$SecurePassword = Read-host -AsSecureString | ConvertFrom-SecureString
$SecurePassword | Out-File -FilePath "C:\Encrypted.key"
To use the the passwords in a script use the get-content:
$username = "Administrator"
$password = Get-Content "C:\Encrypted.key" | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PsCredential($username,$password)
If you want to encrypt the username and password you can do the following:
$securecred = Get-Credential
$securecred.UserName | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | set-content
"C:\Username.key"
$securecred.Password | ConvertFrom-SecureString | set-content "C:\Password.key"
They are stored in separate files
If you want to get the password back as plain text you can use the following:
$password = Get-Content "C:\Encrypted.key" | ConvertTo-SecureString
$plainpassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
Script Writing Info
Find out what escape character to use for special characters:
[Regex]::Escape("<special character>")