powershelladvanced154 snippets

PowerShell: Automate the Boring Stuff

GUIs are for amateurs. Master the One-Liners and Pipelines that manage 100 servers simultaneously. Stop clicking windows and start treating your infrastructure as code.

Sections12
1

🟢 Basic Commands

14 snippets

Fundamentals for starting and interacting with the PowerShell environment, including file system navigation, getting essential information, and accessing documentation.

Get-Location

Displays the full path of the current working directory, functioning like the `pwd` (print working directory) command in Unix/Linux-based systems.

powershell
Get-Location

Set-Location

Changes the current working directory to the specified path. Equivalent to the `cd` (change directory) command. Can be used with absolute or relative paths.

powershell
Set-Location C:\Users

Get-ChildItem

Lists files and subdirectories in the current directory or the specified path. Similar to the `ls` command in Unix/Linux systems or `dir` in the Windows command prompt.

powershell
Get-ChildItem

Get-ChildItem -Force

Lists files and directories, including hidden and system items that are normally omitted. The `-Force` parameter is crucial for revealing these items.

powershell
Get-ChildItem -Force

Get-ChildItem -Recurse

Lists files and directories recursively, traversing all subdirectories from the specified path. Useful for exploring the complete structure of a folder.

powershell
Get-ChildItem -Recurse

Get-ComputerInfo

Collects and displays detailed information about the operating system and local computer hardware, such as OS version, manufacturer, model, RAM, and processor.

powershell
Get-ComputerInfo

Get-Process

Lists all running processes on the system, providing details such as process ID (PID), name, CPU and memory usage. Essential for monitoring and diagnosis.

powershell
Get-Process

Get-Service

Displays a list of all installed services on the system, showing their status (running, stopped, etc.) and display name. Fundamental for service management.

powershell
Get-Service

Get-EventLog -LogName Application

Retrieves events from a specific event log. In this example, it lists events from the Application log, which records events generated by applications and programs.

powershell
Get-EventLog -LogName Application

Get-HotFix

Lists all installed updates (hotfixes) on the Windows operating system, including the update ID, who installed it, and the installation date.

powershell
Get-HotFix

Get-Help

Provides detailed information about a specific cmdlet or function. Use `-Full` for all details, `-Examples` for usage examples, and `-Online` to open online documentation.

powershell
Get-Help Get-Process

Get-Command

Displays information about cmdlets, functions, aliases, and scripts available in PowerShell. Useful for discovering commands and understanding their parameters.

powershell
Get-Command Get-Process

Update-Help

Downloads and installs the latest help files for PowerShell modules. It is recommended to run this command regularly to access updated documentation.

powershell
Update-Help

Get-Module -ListAvailable

Lists all PowerShell modules that are available on the system, including those not yet loaded into the current session.

powershell
Get-Module -ListAvailable
2

📁 File Management

14 snippets

Essential commands for creating, removing, copying, moving, renaming, and manipulating file and directory contents.

New-Item (File)

Creates a new file at the specified path. The `-ItemType File` parameter indicates that a file should be created.

powershell
New-Item -Path "arquivo.txt" -ItemType File

New-Item (Directory)

Creates a new directory (folder) at the specified path. The `-ItemType Directory` parameter indicates that a directory should be created.

powershell
New-Item -Path "pasta" -ItemType Directory

Remove-Item (File)

Deletes a specific file. By default, it will prompt for confirmation before removing the item.

powershell
Remove-Item "arquivo.txt"

Remove-Item (Directory)

Deletes a directory and all its contents (subdirectories and files). The `-Recurse` parameter is mandatory to remove non-empty directories.

powershell
Remove-Item "pasta" -Recurse

Remove-Item -Force

Forces the removal of a file or directory, ignoring warnings and confirmation prompts, even if the item is in use or read-only. Use with caution.

powershell
Remove-Item "arquivo.txt" -Force

Copy-Item (File)

Copies a file from one location to another. If the destination is a file name, it will be copied with that new name. If it's a directory, the file will retain its original name.

powershell
Copy-Item "origem.txt" "destino.txt"

Copy-Item (Directory)

Copies a directory and all its contents (subdirectories and files) to a new location. The `-Recurse` parameter is required to copy entire directories.

powershell
Copy-Item "pasta" "destino" -Recurse

Move-Item

Moves a file or directory from one location to another. Can also be used to rename an item by moving it to the same directory with a new name.

powershell
Move-Item "antigo.txt" "novo.txt"

Rename-Item

Renames a file or directory without changing its location. The first argument is the path of the current item, and the second is the new name.

powershell
Rename-Item "antigo.txt" "novo.txt"

Get-Content

Reads the content of a text file and displays it in the console or passes it to the pipeline for further processing. Useful for viewing logs or data.

powershell
Get-Content "arquivo.txt"

Get-Content (First Lines)

Reads the content of a file and, using the pipeline with `Select-Object -First`, displays only the first 10 lines, useful for large files.

powershell
Get-Content "arquivo.txt" | Select-Object -First 10

Set-Content

Writes or overwrites the content of a file. If the file does not exist, it will be created. If it exists, its previous content will be entirely replaced.

powershell
Set-Content "arquivo.txt" "conteúdo"

Add-Content

Appends content to the end of an existing file. If the file does not exist, it will be created. Preserves the file's previous content.

powershell
Add-Content "arquivo.txt" "mais conteúdo"

Out-File

Redirects the output of a command to a file. For example, `Get-Process | Out-File "processos.txt"` would save the process list to the file.

powershell
Out-File "saida.txt"
3

🔤 Variables and Types

17 snippets

How to declare variables, manipulate different data types like strings, integers, booleans, and use collection structures like arrays and hash tables.

String Variable

Declares a variable `$nome` and assigns it a string (text) value. Variables in PowerShell start with `$`.

powershell
$nome = "João"

Integer Variable

Declares a variable `$idade` and assigns it an integer (whole number) value.

powershell
$idade = 25

Decimal Variable

Declares a variable `$altura` and assigns it a decimal (number with decimal places) value.

powershell
$altura = 1.75

Boolean Variable

Declares a variable `$ativo` and assigns it a boolean value, which can be `$true` (true) or `$false` (false).

powershell
$ativo = $true

Null Variable

Declares a variable `$dados` and assigns it the value `$null`, indicating the absence of a value or object.

powershell
$dados = $null

String Array

Creates an array (ordered list) of strings. The `@()` operator is used to define an array literal.

powershell
$lista = @("item1", "item2", "item3")

Number Array (Range)

Creates an array of integers from 1 to 10 using the range operator (`..`).

powershell
$numeros = 1..10

Access Array Element

Accesses a specific element of an array using its index (position). PowerShell uses zero-based indexing, so `[0]` accesses the first element.

powershell
$lista[0]

Last Array Element

Accesses the last element of an array using negative indexing. `-1` refers to the last element, `-2` to the second to last, and so on.

powershell
$lista[-1]

Array Size

Returns the number of elements (size) of an array using the `.Count` property.

powershell
$lista.Count

Add Element to Array

Adds a new element to the end of an array. Note that this creates a new array with the added element, it does not modify the original array in-place.

powershell
$lista += "novo"

Create Hashtable

Creates a hashtable (dictionary or map), which is a collection of key-value pairs. Keys are unique, and values can be of any type.

powershell
$pessoa = @{Nome="João"; Idade=25}

Access Hashtable by Dot Notation

Accesses the value associated with a key in a hashtable using dot notation, if the key is a valid property name.

powershell
$pessoa.Nome

Access Hashtable by Key

Accesses the value associated with a key in a hashtable using bracket notation and the key name as a string. Works for any key, including those with special characters.

powershell
$pessoa["Nome"]

Add Property to Hashtable

Adds a new key-value pair to an existing hashtable or updates the value of an existing key.

powershell
$pessoa.Cidade = "São Paulo"

List Hashtable Keys

Returns a collection of all keys present in the hashtable.

powershell
$pessoa.Keys

List Hashtable Values

Returns a collection of all values present in the hashtable.

powershell
$pessoa.Values
4

🔀 Control Structures

8 snippets

Commands for controlling script execution flow, enabling conditional decisions and code block repetition.

Simple If/Else

Executes a code block if a condition is true (`if`) and another block if the condition is false (`else`). The `-ge` operator means "greater than or equal to".

powershell
if ($idade -ge 18) {
    Write-Host "Maior de idade"
} else {
    Write-Host "Menor de idade"
}

Multiple If/Elseif/Else

Allows testing multiple conditions in sequence. The `elseif` block is executed if the previous condition is false and its own condition is true.

powershell
if ($nota -ge 7) {
    Write-Host "Aprovado"
} elseif ($nota -ge 5) {
    Write-Host "Recuperação"
} else {
    Write-Host "Reprovado"
}

Traditional For Loop

Executes a block of code a specified number of times. It consists of an initialization, a termination condition, and an increment/decrement expression.

powershell
for ($i = 1; $i -le 10; $i++) {
    Write-Host $i
}

Foreach Loop

Iterates over each item in a collection (such as an array or the result of a cmdlet), executing a block of code for each item.

powershell
foreach ($item in $lista) {
    Write-Host $item
}

Foreach Loop (Iterate Files)

Demonstrates the use of `foreach` to iterate over objects returned by `Get-ChildItem`, displaying the name of each file or directory.

powershell
foreach ($arquivo in Get-ChildItem) {
    Write-Host $arquivo.Name
}

While Loop

Executes a block of code repeatedly as long as a specified condition is true. The condition is evaluated before each iteration.

powershell
$contador = 0
while ($contador -lt 5) {
    Write-Host $contador
    $contador++
}

Do-While Loop

Executes a block of code at least once and then repeats as long as a specified condition is true. The condition is evaluated after each iteration.

powershell
do {
    $resposta = Read-Host "Digite 'sair' para parar"
} while ($resposta -ne "sair")

Switch Case

Allows comparing a value against multiple patterns and executing a code block corresponding to the first matching pattern. The `default` block is executed if no match is found.

powershell
switch ($opcao) {
    1 { Write-Host "Opção 1" }
    2 { Write-Host "Opção 2" }
    default { Write-Host "Opção inválida" }
}
5

⚡ Functions and Scripts

9 snippets

Creating and using functions to modularize code, define advanced parameters, and organize scripts into reusable modules.

Simple Function

Defines a function named `Saudar` that accepts a string parameter `$nome` and displays a personalized greeting.

powershell
function Saudar($nome) {
    param([string]$nome)
    Write-Host "Olá, $nome!"
}

Function with Typed Parameters

Defines a function that calculates the area of a triangle, specifying the data types (`[double]`) for the `$base` and `$altura` parameters and returning a value.

powershell
function Calcular-Area($base, $altura) {
    param([double]$base, [double]$altura)
    return ($base * $altura) / 2
}

Function with Default Parameter

Defines a function where the `$servidor` parameter has a default value of "localhost". If the user does not provide a value for `$servidor`, the default will be used.

powershell
function Testar-Conexao {
    param([string]$servidor = "localhost")
    Test-Connection $servidor
}

Advanced Parameters

Example of how to use advanced parameter attributes: `Mandatory=$true` makes the `$Caminho` parameter mandatory, and `[switch]$Recurse` creates a boolean parameter without the need for a value.

powershell
function Processar-Arquivos {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Caminho,
        
        [Parameter()]
        [switch]$Recurse
    )
    # Código da função
}

Parameter that Accepts Pipeline

Demonstrates a parameter that can receive pipeline input (`ValueFromPipeline=$true`). This allows the function to process objects passed from other cmdlets.

powershell
function Exportar-Dados {
    param(
        [Parameter(ValueFromPipeline=$true)]
        [object[]]$Dados
    )
    $Dados | Export-Csv -Path "saida.csv"
}

Import Script

Executes a PowerShell script in the current session's scope. The dot (`.`) and space are essential for variables and functions defined in the script to be available in the session.

powershell
. .\meu-script.ps1

Import Module

Loads a PowerShell module into the current session, making its cmdlets, functions, and variables available. Modules are the preferred way to organize and distribute PowerShell code.

powershell
Import-Module .\meu-modulo.psm1

Export Module Function

Specifies which functions, cmdlets, variables, or aliases from a module should be exported and made public for use by other sessions after the module is imported.

powershell
Export-ModuleMember -Function MinhaFuncao

$PSVersionTable

An automatic variable that displays details about the PowerShell version, edition, .NET Framework version, and other runtime environment information.

powershell
$PSVersionTable
6

🔄 Pipeline and Operators

20 snippets

Leverage the power of PowerShell pipeline to chain commands and use comparison and logical operators to filter and manipulate data efficiently.

Filter Processes by CPU

Gets all processes and, via pipeline (`|`), filters them using `Where-Object` to select only those whose CPU utilization (`$_.CPU`) is greater than 100 seconds.

powershell
Get-Process | Where-Object {$_.CPU -gt 100}

Filter Files by Extension

Lists all items in the current directory and filters them to display only those with the ".txt" extension (`$_.Extension -eq ".txt"`).

powershell
Get-ChildItem | Where-Object {$_.Extension -eq ".txt"}

Filter Running Services

Gets all services and filters them to show only those whose status (`$_.Status`) is "Running".

powershell
Get-Service | Where-Object {$_.Status -eq "Running"}

Sort Processes by CPU

Lists all processes and sorts them based on CPU utilization (`CPU`), in descending order (`-Descending`), showing the most intensive processes first.

powershell
Get-Process | Sort-Object CPU -Descending

Operator -eq (Equal)

Comparison operator that checks if two values are equal. Returns `$true` if they are equal, `$false` otherwise.

powershell
$a -eq $b

Operator -ne (Not Equal)

Comparison operator that checks if two values are different. Returns `$true` if they are different, `$false` otherwise.

powershell
$a -ne $b

Operator -gt (Greater than)

Comparison operator that checks if the left value is strictly greater than the right value.

powershell
$a -gt $b

Operator -ge (Greater than or Equal)

Comparison operator that checks if the left value is greater than or equal to the right value.

powershell
$a -ge $b

Operator -lt (Less than)

Comparison operator that checks if the left value is strictly less than the right value.

powershell
$a -lt $b

Operator -le (Less than or Equal)

Comparison operator that checks if the left value is less than or equal to the right value.

powershell
$a -le $b

Operator -like (Contains Wildcard)

Comparison operator that uses wildcards like `*` and `?` to find patterns in strings. Returns `$true` if string `$a` contains "text".

powershell
$a -like "*texto*"

Operador -match (Regex)

Operador de comparação que usa expressões regulares (regex) para encontrar padrões em strings. Retorna `$true` se a string `$a` corresponder ao padrão regex.

powershell
$a -match "regex"

Operator -and (Logical AND)

Logical operator that returns `$true` if both expressions `$a` and `$b` are true. Otherwise, returns `$false`.

powershell
$a -and $b

Operator -or (Logical OR)

Logical operator that returns `$true` if at least one of expressions `$a` or `$b` is true. Returns `$false` only if both are false.

powershell
$a -or $b

Operator -not (Negation)

Logical operator that inverts the boolean value of an expression. If `$a` is `$true`, `-not $a` will be `$false`, and vice-versa.

powershell
-not $a

Operator -xor (Exclusive OR)

Logical operator that returns `$true` if only one of expressions `$a` or `$b` is true, but not both. Returns `$false` if both are true or both are false.

powershell
$a -xor $b

Select-Object (Properties)

Selects specific properties of objects in the pipeline. In this example, it displays only the name, CPU, and memory of each process.

powershell
Get-Process | Select-Object Name, CPU, Memory

Select-Object -First

Selects only the first `N` objects from the pipeline. Useful for limiting output or getting data samples.

powershell
Get-Process | Select-Object -First 10

Select-Object -Last

Selects only the last `N` objects from the pipeline. Useful for viewing the most recent or final items in a list.

powershell
Get-Process | Select-Object -Last 5

Select-Object -Unique

Removes duplicate objects from the pipeline, ensuring that each object in the output is unique. Useful for getting a distinct list of values.

powershell
Get-Process | Select-Object -Unique
7

⚙️ Process Management

14 snippets

Commands for listing, monitoring, starting, and terminating processes and services on Windows, essential for administration and troubleshooting.

Get-Process (All)

Lists all processes currently running on the system, providing information such as ID, name, CPU, and memory usage.

powershell
Get-Process

Get-Process (Specific)

Gets information about processes with a specific name. Wildcards can be used, such as `"chrome*"` for all processes starting with "chrome".

powershell
Get-Process -Name "chrome"

Get-Process (Intensive)

Filters and displays processes that have consumed more than 100 seconds of CPU time, helping to identify processes that are overloading the system.

powershell
Get-Process | Where-Object {$_.CPU -gt 100}

Top 10 Processes by CPU

Lists the top 10 CPU-consuming processes, sorted in descending order. Useful for identifying performance bottlenecks.

powershell
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10

Start-Process (No Parameters)

Starts a new process on the system. In this example, it opens Notepad.

powershell
Start-Process notepad.exe

Start-Process (With Parameter)

Starts a process and passes arguments to it. Here, Chrome is opened and navigates directly to google.com.

powershell
Start-Process chrome.exe "https://google.com"

Stop-Process (By Name)

Terminates a process with a specific name. By default, it will prompt for confirmation. Use `-Force` to force termination.

powershell
Stop-Process -Name "notepad"

Stop-Process (By ID)

Terminates a process using its unique ID (PID). This method is more precise than using the name, especially when there are multiple processes with the same name.

powershell
Stop-Process -Id 1234

Stop-Process -Force

Forces the termination of a process by name, ignoring confirmation prompts and graceful shutdown attempts. Use with caution, as it may result in data loss.

powershell
Stop-Process -Name "chrome" -Force

Get-Service (All)

Lists all services installed on the system, including their current status (running, stopped) and display name.

powershell
Get-Service

Get-Service (Specific)

Gets information about a specific service by its name. Useful for checking the status or properties of an individual service.

powershell
Get-Service -Name "Spooler"

Start-Service

Starts a stopped service. The "Spooler" service is the Windows Print Spooler service.

powershell
Start-Service -Name "Spooler"

Stop-Service

Stops a running service. By default, it will prompt for confirmation. Use `-Force` to force the stop.

powershell
Stop-Service -Name "Spooler"

Restart-Service

Restarts a service, first stopping it and then starting it again. Useful for applying configurations or resolving temporary issues.

powershell
Restart-Service -Name "Spooler"
8

🌐 Network and Connectivity

13 snippets

Commands for diagnosing, configuring, and interacting with the network, including adapters, IP addresses, firewall, and HTTP/REST requests.

Get-NetAdapter

Lists all network adapters installed on the system, providing information such as name, status, speed, and media type.

powershell
Get-NetAdapter

Get-NetIPAddress

Displays the IP addresses (IPv4 and IPv6) configured on each network adapter, along with the subnet prefix and default gateway.

powershell
Get-NetIPAddress

Get-NetRoute

Displays the system's IP routing table, showing how network traffic is directed to different destinations.

powershell
Get-NetRoute

Test-Connection

Sends ICMP (ping) packets to a remote host to check network connectivity. Returns details about response time and connection status.

powershell
Test-Connection google.com

Test-NetConnection

Tests network connectivity to a specific host and port. Useful for checking if a service is accessible on a port, such as HTTP (port 80).

powershell
Test-NetConnection google.com -Port 80

New-NetIPAddress

Configures a new static IP address on a network adapter. `-InterfaceAlias` specifies the adapter, `-IPAddress` the address, and `-PrefixLength` the subnet mask.

powershell
New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress 192.168.1.100 -PrefixLength 24

Set-DnsClientServerAddress

Sets the DNS server addresses for a specific network adapter. In this example, it configures the primary DNS to Google's public DNS.

powershell
Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses 8.8.8.8

Get-NetFirewallRule

Lists all Windows Defender Firewall rules, including inbound and outbound rules, affected programs, and ports.

powershell
Get-NetFirewallRule

New-NetFirewallRule

Creates a new firewall rule. This example creates an inbound rule to allow RDP connections (TCP port 3389).

powershell
New-NetFirewallRule -DisplayName "Permitir RDP" -Direction Inbound -Protocol TCP -LocalPort 3389 -Action Allow

Invoke-WebRequest

Sends an HTTP/HTTPS request to a web resource. Returns an object containing the response status, headers, and content. Useful for interacting with APIs or downloading pages.

powershell
Invoke-WebRequest https://api.example.com

Invoke-RestMethod

Sends an HTTP/HTTPS request and converts the response (usually JSON or XML) directly into a PowerShell object, facilitating data manipulation from RESTful APIs.

powershell
Invoke-RestMethod https://api.example.com/data

Invoke-WebRequest (Get Content)

Performs a web request and stores the response object in a variable. Then, accesses the `.Content` property to get the response body as a string.

powershell
$response = Invoke-WebRequest https://example.com
$response.Content

Invoke-WebRequest (Download)

Downloads content from a URL and saves it directly to a local file. The `-OutFile` parameter specifies the path and name of the destination file.

powershell
Invoke-WebRequest https://example.com -OutFile "pagina.html"
9

👥 Active Directory

13 snippets

Commands for managing users, groups, and performing advanced Active Directory queries, essential for domain administrators and IT automation.

Get-ADUser (All)

Lists all user objects in Active Directory. The `*` filter indicates that all users should be returned.

powershell
Get-ADUser -Filter *

Get-ADUser (Specific)

Gets detailed information about a specific Active Directory user, using their SamAccountName, DistinguishedName, SID, or GUID.

powershell
Get-ADUser -Identity "joao.silva"

New-ADUser

Creates a new user object in Active Directory. It is necessary to provide at least `-Name` and `-SamAccountName`. It is also recommended to set a password and the OU path.

powershell
New-ADUser -Name "novo.usuario" -SamAccountName "novo.usuario" -GivenName "Novo" -Surname "Usuario" -AccountPassword (Convert-ToSecureString "Senha@123" -AsPlainText -Force) -Enabled $true -Path "OU=Usuarios,DC=dominio,DC=local"

Set-ADUser

Modifies the properties of an existing user in Active Directory. Use `-Identity` to specify the user and parameters for the properties to be changed.

powershell
Set-ADUser -Identity "joao.silva" -Department "TI" -Office "Sala 101"

Disable-ADAccount

Disables a user account in Active Directory, preventing the user from logging into the domain. The account remains in AD, but inactive.

powershell
Disable-ADAccount -Identity "joao.silva"

Get-ADGroup (All)

Lists all group objects in Active Directory. The `*` filter indicates that all groups should be returned.

powershell
Get-ADGroup -Filter *

Get-ADGroupMember

Lists all members (users and/or other groups) of a specific Active Directory group. The group name can be the SamAccountName or DistinguishedName.

powershell
Get-ADGroupMember "TI"

Add-ADGroupMember

Adds one or more users or groups to an existing Active Directory group. `-Identity` specifies the group and `-Members` the objects to be added.

powershell
Add-ADGroupMember -Identity "TI" -Members "joao.silva"

Remove-ADGroupMember

Removes one or more users or groups from an existing Active Directory group. `-Identity` specifies the group and `-Members` the objects to be removed.

powershell
Remove-ADGroupMember -Identity "TI" -Members "joao.silva"

Search-ADAccount (Disabled Accounts)

Searches for accounts in Active Directory based on specific criteria. `-AccountDisabled` returns all user accounts that are disabled.

powershell
Search-ADAccount -AccountDisabled

Get-ADUser (Non-Expiring Passwords)

Filters users in Active Directory to find those whose password is set to never expire. The `-Properties` parameter is required to display this property.

powershell
Get-ADUser -Filter {PasswordNeverExpires -eq $true} -Properties PasswordNeverExpires

Get-ADUser (Inactive 90 Days)

Filters users who have not logged on for more than 90 days. `-Properties LastLogonDate` is required for the property to be returned and filtered.

powershell
Get-ADUser -Filter {LastLogonDate -lt (Get-Date).AddDays(-90)} -Properties LastLogonDate

Export Users to CSV

Exports all Active Directory users, with all their properties (`-Properties *`), to a CSV file. `-NoTypeInformation` prevents the type information line in the file.

powershell
Get-ADUser -Filter * -Properties * | Export-Csv "usuarios.csv" -NoTypeInformation
10

🔒 Security and Permissions

10 snippets

Managing script execution policies, code signing, and file access control, ensuring PowerShell environment security and integrity.

Get-ExecutionPolicy

Displays the current PowerShell execution policy, which determines which scripts can be run and under what conditions. Policies include `Restricted`, `RemoteSigned`, `AllSigned`, and `Bypass`.

powershell
Get-ExecutionPolicy

Set-ExecutionPolicy RemoteSigned

Sets the execution policy to `RemoteSigned`. This allows locally created scripts to run without a signature, but requires scripts downloaded from the internet to be signed by a trusted publisher.

powershell
Set-ExecutionPolicy RemoteSigned

Set-ExecutionPolicy Bypass (Temporary)

Sets the execution policy to `Bypass` only for the current PowerShell session (`-Scope Process`). This allows the execution of all scripts without restrictions, but the policy is reverted when the session closes.

powershell
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

Set-ExecutionPolicy AllSigned (Current User)

Sets the execution policy to `AllSigned` for the current user. This requires all scripts, including locally created ones, to be signed by a trusted publisher.

powershell
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy AllSigned

Get-ChildItem Cert:\CurrentUser\My

Lists all digital certificates installed in the current user's "Personal" (My) store. Useful for checking available certificates for code signing.

powershell
Get-ChildItem Cert:\CurrentUser\My

Get-AuthenticodeSignature

Verifies the Authenticode digital signature of a file, such as a PowerShell script. Returns information about the signature status, signatory, and timestamp.

powershell
Get-AuthenticodeSignature "script.ps1"

Set-AuthenticodeSignature

Digitally signs a PowerShell script using an Authenticode certificate. `$cert` must be a variable containing the certificate obtained, for example, via `Get-ChildItem Cert:\...`.

powershell
Set-AuthenticodeSignature -FilePath "script.ps1" -Certificate $cert

Get-Acl (Folder Permissions)

Displays the Access Control Lists (ACLs), or security permissions, of a file or directory. Shows owner, group, and access rules.

powershell
Get-Acl "C:\pasta"

Set File/Folder Permission

Sets a new permission rule for a file or folder. This example grants full control (`FullControl`) to "User" on the "C:\folder" folder.

powershell
$acl = Get-Acl "C:\pasta"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Usuario","FullControl","Allow")
$acl.SetAccessRule($accessRule)
Set-Acl "C:\pasta" $acl

Get-Acl (Detailed)

Displays file or folder permissions in a detailed list format, showing all Access Control Entries (ACEs) in a more readable way.

powershell
Get-Acl "arquivo.txt" | Format-List
11

⏰ Automation and Scheduling

11 snippets

Techniques for automating repetitive tasks, scheduling script execution, and managing background jobs to optimize operational efficiency.

Get-ScheduledTask

Lists all scheduled tasks configured on the Windows operating system, including their status, name, and next run time.

powershell
Get-ScheduledTask

Register-ScheduledTask

Creates a new scheduled task. This example creates a task that runs `notepad.exe` daily at 9 AM. `New-ScheduledTaskAction` defines the action and `New-ScheduledTaskTrigger` defines the trigger.

powershell
Register-ScheduledTask -Action (New-ScheduledTaskAction -Execute "notepad.exe") -Trigger (New-ScheduledTaskTrigger -Daily -At 9am) -TaskName "AbrirNotepadDiariamente" -Description "Abre o Bloco de Notas todos os dias às 9h."

Start-ScheduledTask

Starts the execution of a scheduled task manually, regardless of its programmed trigger.

powershell
Start-ScheduledTask -TaskName "MinhaTarefa"

Disable-ScheduledTask

Disables a scheduled task, preventing it from being executed by its triggers. The task remains in the system, but in an inactive state.

powershell
Disable-ScheduledTask -TaskName "MinhaTarefa"

Unregister-ScheduledTask

Permanently removes a scheduled task from the system. The `-Confirm:$false` parameter prevents the confirmation prompt.

powershell
Unregister-ScheduledTask -TaskName "MinhaTarefa" -Confirm:$false

Start-Job

Starts a script or command in the background as a job. The `-ScriptBlock` contains the code to be executed, and `-Name` assigns a name to the job.

powershell
Start-Job -ScriptBlock { Get-Process } -Name "ProcessosJob"

Get-Job

Lists all background jobs that are running or have completed in the current PowerShell session.

powershell
Get-Job

Receive-Job

Retrieves the results of a background job. After retrieval, the results are removed from the job. Use `-Keep` to retain the results.

powershell
Receive-Job -Id 1

Stop-Job

Terminates a running background job. It may be necessary to use `-Force` for unresponsive jobs.

powershell
Stop-Job -Id 1

Remove-Job

Removes a background job from the current PowerShell session. This frees up resources associated with the job.

powershell
Remove-Job -Id 1

Basic Workflow

Defines a PowerShell workflow, which allows tasks to be executed in parallel (`parallel`) or in sequence (`sequence`), with resilience to reboots and support for checkpoints.

powershell
workflow MeuWorkflow {
    parallel {
        Get-Process
        Get-Service
    }
    sequence {
        Write-Host "Concluído"
    }
}
12

🖥️ WMI and CIM

11 snippets

Exploring and manipulating Windows system information using WMI and CIM for advanced monitoring, inventory, and diagnostics.

Get-WmiObject (OS Info)

Queries WMI to get detailed information about the Windows operating system, such as version, service pack, installation date, and manufacturer.

powershell
Get-WmiObject -Class Win32_OperatingSystem

Get-WmiObject (Hardware Info)

Queries WMI to get general information about the computer system, including manufacturer name, model, domain name, and total physical memory.

powershell
Get-WmiObject -Class Win32_ComputerSystem

Get-WmiObject (CPU Info)

Queries WMI to get details about the system's processor(s), such as manufacturer, speed, number of cores, and architecture.

powershell
Get-WmiObject -Class Win32_Processor

Get-WmiObject (Disk Info)

Queries WMI to get information about the system's logical disks (partitions), such as drive letter, total size, free space, and file system type.

powershell
Get-WmiObject -Class Win32_LogicalDisk

Get-CimInstance (Modern CIM)

Modern cmdlet for querying CIM (Common Information Model) classes, which is the evolution of WMI. Offers better performance and remote session support. Equivalent to `Get-WmiObject`.

powershell
Get-CimInstance -ClassName Win32_OperatingSystem

Get-CimInstance (CIM Query)

Executes a WQL (WMI Query Language) query directly to filter CIM objects. This example selects all processes with the name "chrome.exe".

powershell
Get-CimInstance -Query "SELECT * FROM Win32_Process WHERE Name = 'chrome.exe'"

New-CimSession (Remote Session)

Creates a new CIM session for a remote computer, allowing CIM cmdlets to be executed against that system. Requires permissions and network connectivity.

powershell
New-CimSession -ComputerName servidor

Get-CimInstance (Remote Query)

Executes a CIM query on a remote computer using a previously established CIM session (`$session`). This example lists the services on the remote server.

powershell
Get-CimInstance -CimSession $session -ClassName Win32_Service

Get-EventLog (Latest Events)

Retrieves the 10 most recent events from the system event log. Useful for a quick check of recent events.

powershell
Get-EventLog -LogName System -Newest 10

Get-WinEvent (Error Events)

A more advanced cmdlet for accessing event logs. This example filters Application log events with an error level (Level 2).

powershell
Get-WinEvent -FilterHashtable @{LogName='Application'; Level=2}

Get-Counter (Performance Counter)

Gets data from system performance counters. This example monitors total processor utilization time in real-time.

powershell
Get-Counter "\Processor(_Total)\% Processor Time"

Get the latest articles delivered to your inbox.

Follow Us: