Skip to content

AlgoArchives/PowerShell-Commands

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 

Repository files navigation

PowerShell-Commands

1. File and Folder Operations

List Files and Directories

Get-ChildItem -Path "C:\Path\To\Directory"

Create a New File

New-Item -Path "C:\Path\To\File.txt" -ItemType File

Create a New Folder

New-Item -Path "C:\Path\To\NewFolder" -ItemType Directory

Copy a File

Copy-Item -Path "C:\Path\To\Source\File.txt" -Destination "C:\Path\To\Destination\"

Move a File

Move-Item -Path "C:\Path\To\Source\File.txt" -Destination "C:\Path\To\Destination\"

Remove a File

Remove-Item -Path "C:\Path\To\File.txt"

Remove a Folder

Remove-Item -Path "C:\Path\To\Folder" -Recurse

Get File or Folder Properties

Get-Item -Path "C:\Path\To\FileOrFolder" | Select-Object *

Get Directory Size

Get-ChildItem -Path "C:\Path\To\Directory" -Recurse | Measure-Object -Property Length -Sum

2. System Information

Get System Information

Get-ComputerInfo

Get Operating System Information

Get-WmiObject -Class Win32_OperatingSystem

Get Installed Hotfixes

Get-HotFix

Get List of Installed Programs

Get-WmiObject -Class Win32_Product

Get CPU Information

Get-WmiObject -Class Win32_Processor

Get Memory (RAM) Information

Get-WmiObject -Class Win32_PhysicalMemory

Get Disk Space Information

Get-PSDrive -PSProvider FileSystem

Check if a Service is Running

Get-Service -Name "ServiceName"

Get Startup Programs

Get-CimInstance -ClassName Win32_StartupCommand | Select-Object Name, Command, User

3. Networking

Get IP Configuration

Get-NetIPAddress

Get Active Network Adapters

Get-NetAdapter | Where-Object {$_.Status -eq 'Up'}

Test Network Connection (Ping)

Test-Connection -ComputerName "google.com"

Get Open Ports

Get-NetTCPConnection | Where-Object { $_.State -eq "Listen" }

Get DNS Servers

Get-DnsClientServerAddress

Get Network Interface Details

Get-NetIPConfiguration

Get Routing Table

Get-NetRoute

Disable a Network Adapter

Disable-NetAdapter -Name "Ethernet"

Enable a Network Adapter

Enable-NetAdapter -Name "Ethernet"

4. Process Management

Get Running Processes

Get-Process

Stop a Process by Name

Stop-Process -Name "ProcessName"

Start a Process

Start-Process -FilePath "C:\Path\To\Program.exe"

Get Process by ID

Get-Process -Id 1234

Get Process with High CPU Usage

Get-Process | Sort-Object CPU -Descending | Select-Object -First 5

Kill a Process by ID

Stop-Process -Id 1234

5. User and System Management

Create a New Local User

New-LocalUser "Username" -Password (ConvertTo-SecureString "Password" -AsPlainText -Force) -FullName "Full Name" -Description "User Description"

Add a User to a Group

Add-LocalGroupMember -Group "Administrators" -Member "Username"

List Local Users

Get-LocalUser

List Local Groups

Get-LocalGroup

Disable a Local User Account

Disable-LocalUser -Name "Username"

Enable a Local User Account

Enable-LocalUser -Name "Username"

6. Windows Services

List All Services

Get-Service

Start a Service

Start-Service -Name "ServiceName"

Stop a Service

Stop-Service -Name "ServiceName"

Restart a Service

Restart-Service -Name "ServiceName"

Get Service Status

Get-Service -Name "ServiceName"

Set a Service to Start Automatically

Set-Service -Name "ServiceName" -StartupType Automatic

7. PowerShell Session and Environment

Start Remote Session

Enter-PSSession -ComputerName "RemoteComputerName"

Exit Remote Session

Exit-PSSession

Execute Command on Remote Computer

Invoke-Command -ComputerName "RemoteComputerName" -ScriptBlock { Get-Process }

List Environment Variables

Get-ChildItem Env:

Set an Environment Variable

[System.Environment]::SetEnvironmentVariable("VariableName", "VariableValue", "User")

8. Scripting and Automation

Create a PowerShell Script

# Save this in a file with the extension .ps1
Write-Output "Hello, World!"

Execute a PowerShell Script

.\script.ps1

Schedule a Task (using Task Scheduler)

schtasks /create /tn "TaskName" /tr "C:\Path\To\script.ps1" /sc daily /st 09:00

Run a Script with Administrator Privileges

Start-Process powershell.exe -ArgumentList "Start-Process -Verb RunAs 'C:\Path\To\script.ps1'"

9. Windows Updates

Check for Updates

Install-Module PSWindowsUpdate
Get-WindowsUpdate

Install Updates

Install-WindowsUpdate -AcceptAll

Hide a Windows Update

Hide-WindowsUpdate -KBArticleID "KB1234567"

10. Miscellaneous Commands

Generate a Random Password

[System.Web.Security.Membership]::GeneratePassword(12, 2)

Get PowerShell Version

$PSVersionTable.PSVersion

Clear PowerShell Console

Clear-Host

Export Output to CSV

Get-Process | Export-Csv -Path "C:\Path\To\Output.csv" -NoTypeInformation

11. Help and Documentation

Get Help for a Command

Get-Help Get-Process

Update Help Files

Update-Help

12. Development and Debugging

Get Installed Modules

Get-Module -ListAvailable

Import a Module

Import-Module "ModuleName"

Find a Module from the PowerShell Gallery

Find-Module -Name "ModuleName"

Install a Module from PowerShell Gallery

Install-Module -Name "ModuleName"

Remove a Module

Remove-Module -Name "ModuleName"

Export a Module Member

Export-ModuleMember -Function "FunctionName" -Alias "AliasName"

13. Version Control (Git) with PowerShell

Clone a Git Repository

git clone https://github.com/username/repo.git

Check Git Status

git status

Stage Files for Commit

git add .

Commit Changes

git commit -m "Your commit message"

Push Changes to Remote Repository

git push origin main

Pull Latest Changes

git pull origin main

Create a New Branch

git checkout -b "new-branch-name"

Merge a Branch

git merge "branch-name"

14. Security and Encryption

Encrypt a Password

$SecurePassword = Read-Host -AsSecureString

Convert Secure Password to Plain Text (for Testing Only!)

[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword))

Convert a String to a Secure String

$SecureString = ConvertTo-SecureString "yourpassword" -AsPlainText -Force

Create Self-Signed Certificate

New-SelfSignedCertificate -DnsName "www.example.com" -CertStoreLocation "cert:\LocalMachine\My"

Add a Trusted Root Certificate Authority

Import-Certificate -FilePath "C:\Path\To\Certificate.cer" -CertStoreLocation Cert:\LocalMachine\Root

15. Error Handling and Debugging

Try/Catch Block for Error Handling

try {
    # Code that might throw an exception
    $result = Get-Process -Name "NonExistentProcess"
} catch {
    Write-Host "Error occurred: $_"
}

Display Errors in PowerShell

$Error

Clear Error Buffer

$Error.Clear()

Set Error Action Preference to Stop

$ErrorActionPreference = "Stop"

Check Last Error

$?

16. Working with APIs

Invoke a REST API (GET Request)

Invoke-RestMethod -Uri "https://api.example.com/data" -Method Get

Send POST Request to API

Invoke-RestMethod -Uri "https://api.example.com/data" -Method Post -Body $jsonBody -ContentType "application/json"

Convert JSON to PowerShell Object

$json = '{"name": "John", "age": 30}'
ConvertFrom-Json $json

Convert PowerShell Object to JSON

$object = @{ name = "John"; age = 30 }
$object | ConvertTo-Json

17. Performance Monitoring

Get CPU Usage

Get-WmiObject -Class Win32_Processor | Select-Object -Property LoadPercentage

Get Memory Usage

Get-WmiObject -Class Win32_OperatingSystem | Select-Object -Property TotalVisibleMemorySize, FreePhysicalMemory

Monitor Disk Performance

Get-Counter -Counter "\PhysicalDisk(_Total)\% Disk Time"

Monitor Network Interface Throughput

Get-Counter -Counter "\Network Interface(*)\Bytes Total/sec"

Measure Script Execution Time

Measure-Command { # Your script block here }

18. Database Management (SQL)

Execute SQL Query (using SQL Server)

Invoke-Sqlcmd -Query "SELECT * FROM YourTable" -ServerInstance "ServerName" -Database "DatabaseName"

Export SQL Query Results to CSV

Invoke-Sqlcmd -Query "SELECT * FROM YourTable" -ServerInstance "ServerName" -Database "DatabaseName" | Export-Csv -Path "C:\Path\To\Export.csv" -NoTypeInformation

Backup a SQL Database

Backup-SqlDatabase -ServerInstance "ServerName" -Database "DatabaseName" -BackupFile "C:\Path\To\Backup.bak"

Restore a SQL Database

Restore-SqlDatabase -ServerInstance "ServerName" -Database "DatabaseName" -BackupFile "C:\Path\To\Backup.bak"

19. File Compression and Archiving

Compress Files into a Zip Archive

Compress-Archive -Path "C:\Path\To\Files\*" -DestinationPath "C:\Path\To\Archive.zip"

Extract a Zip Archive

Expand-Archive -Path "C:\Path\To\Archive.zip" -DestinationPath "C:\Path\To\ExtractedFiles"

20. Working with Active Directory (Requires Active Directory Module)

Import Active Directory Module

Import-Module ActiveDirectory

Get AD Users

Get-ADUser -Filter *

Get AD Groups

Get-ADGroup -Filter *

Add User to Active Directory

New-ADUser -Name "John Doe" -GivenName "John" -Surname "Doe" -SamAccountName "jdoe" -UserPrincipalName "[email protected]" -Path "OU=Users,DC=example,DC=com" -AccountPassword (ConvertTo-SecureString "Password123!" -AsPlainText -Force) -Enabled $true

Remove AD User

Remove-ADUser -Identity "jdoe"

Find Locked AD Accounts

Search-ADAccount -LockedOut

21. Task Automation and Scheduling

Create a Scheduled Task

$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\Path\To\YourScript.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 9am
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "MyScheduledTask" -Description "Runs a PowerShell script daily at 9 AM"

Remove a Scheduled Task

Unregister-ScheduledTask -TaskName "MyScheduledTask" -Confirm:$false

22. Containers (Docker)

List Docker Containers

docker ps

Start a Docker Container

docker start "ContainerNameOrID"

Stop a Docker Container

docker stop "ContainerNameOrID"

Remove a Docker Container

docker rm "ContainerNameOrID"

Pull a Docker Image

docker pull "ImageName"

23. PowerShell Remoting

Enable PowerShell Remoting

Enable-PSRemoting -Force

Establish Remote Session

Enter-PSSession -ComputerName "RemoteComputerName"

Run Command on Remote Machine

Invoke-Command -ComputerName "RemoteComputerName" -ScriptBlock { Get-Process }

Disable PowerShell Remoting

Disable-PSRemoting -Force

Acknowledgment

Some of the PowerShell commands in this repository have been inspired by or sourced from the excellent article "Top 51 PowerShell Commands That You Should Know" by Stackify. This article provides a comprehensive guide for developers and IT professionals to use PowerShell for various administrative and development tasks.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published