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
🟢 Basic Commands
14 snippetsFundamentals 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.
Get-LocationSet-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.
Set-Location C:\UsersGet-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.
Get-ChildItemGet-ChildItem -Force
Lists files and directories, including hidden and system items that are normally omitted. The `-Force` parameter is crucial for revealing these items.
Get-ChildItem -ForceGet-ChildItem -Recurse
Lists files and directories recursively, traversing all subdirectories from the specified path. Useful for exploring the complete structure of a folder.
Get-ChildItem -RecurseGet-ComputerInfo
Collects and displays detailed information about the operating system and local computer hardware, such as OS version, manufacturer, model, RAM, and processor.
Get-ComputerInfoGet-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.
Get-ProcessGet-Service
Displays a list of all installed services on the system, showing their status (running, stopped, etc.) and display name. Fundamental for service management.
Get-ServiceGet-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.
Get-EventLog -LogName ApplicationGet-HotFix
Lists all installed updates (hotfixes) on the Windows operating system, including the update ID, who installed it, and the installation date.
Get-HotFixGet-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.
Get-Help Get-ProcessGet-Command
Displays information about cmdlets, functions, aliases, and scripts available in PowerShell. Useful for discovering commands and understanding their parameters.
Get-Command Get-ProcessUpdate-Help
Downloads and installs the latest help files for PowerShell modules. It is recommended to run this command regularly to access updated documentation.
Update-HelpGet-Module -ListAvailable
Lists all PowerShell modules that are available on the system, including those not yet loaded into the current session.
Get-Module -ListAvailable📁 File Management
14 snippetsEssential 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.
New-Item -Path "arquivo.txt" -ItemType FileNew-Item (Directory)
Creates a new directory (folder) at the specified path. The `-ItemType Directory` parameter indicates that a directory should be created.
New-Item -Path "pasta" -ItemType DirectoryRemove-Item (File)
Deletes a specific file. By default, it will prompt for confirmation before removing the item.
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.
Remove-Item "pasta" -RecurseRemove-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.
Remove-Item "arquivo.txt" -ForceCopy-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.
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.
Copy-Item "pasta" "destino" -RecurseMove-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.
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.
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.
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.
Get-Content "arquivo.txt" | Select-Object -First 10Set-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.
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.
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.
Out-File "saida.txt"🔤 Variables and Types
17 snippetsHow 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 `$`.
$nome = "João"Integer Variable
Declares a variable `$idade` and assigns it an integer (whole number) value.
$idade = 25Decimal Variable
Declares a variable `$altura` and assigns it a decimal (number with decimal places) value.
$altura = 1.75Boolean Variable
Declares a variable `$ativo` and assigns it a boolean value, which can be `$true` (true) or `$false` (false).
$ativo = $trueNull Variable
Declares a variable `$dados` and assigns it the value `$null`, indicating the absence of a value or object.
$dados = $nullString Array
Creates an array (ordered list) of strings. The `@()` operator is used to define an array literal.
$lista = @("item1", "item2", "item3")Number Array (Range)
Creates an array of integers from 1 to 10 using the range operator (`..`).
$numeros = 1..10Access Array Element
Accesses a specific element of an array using its index (position). PowerShell uses zero-based indexing, so `[0]` accesses the first element.
$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.
$lista[-1]Array Size
Returns the number of elements (size) of an array using the `.Count` property.
$lista.CountAdd 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.
$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.
$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.
$pessoa.NomeAccess 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.
$pessoa["Nome"]Add Property to Hashtable
Adds a new key-value pair to an existing hashtable or updates the value of an existing key.
$pessoa.Cidade = "São Paulo"List Hashtable Keys
Returns a collection of all keys present in the hashtable.
$pessoa.KeysList Hashtable Values
Returns a collection of all values present in the hashtable.
$pessoa.Values🔀 Control Structures
8 snippetsCommands 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".
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.
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.
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.
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.
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.
$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.
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.
switch ($opcao) {
1 { Write-Host "Opção 1" }
2 { Write-Host "Opção 2" }
default { Write-Host "Opção inválida" }
}⚡ Functions and Scripts
9 snippetsCreating 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.
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.
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.
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.
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.
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.
. .\meu-script.ps1Import 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.
Import-Module .\meu-modulo.psm1Export 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.
Export-ModuleMember -Function MinhaFuncao$PSVersionTable
An automatic variable that displays details about the PowerShell version, edition, .NET Framework version, and other runtime environment information.
$PSVersionTable🔄 Pipeline and Operators
20 snippetsLeverage 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.
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"`).
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".
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.
Get-Process | Sort-Object CPU -DescendingOperator -eq (Equal)
Comparison operator that checks if two values are equal. Returns `$true` if they are equal, `$false` otherwise.
$a -eq $bOperator -ne (Not Equal)
Comparison operator that checks if two values are different. Returns `$true` if they are different, `$false` otherwise.
$a -ne $bOperator -gt (Greater than)
Comparison operator that checks if the left value is strictly greater than the right value.
$a -gt $bOperator -ge (Greater than or Equal)
Comparison operator that checks if the left value is greater than or equal to the right value.
$a -ge $bOperator -lt (Less than)
Comparison operator that checks if the left value is strictly less than the right value.
$a -lt $bOperator -le (Less than or Equal)
Comparison operator that checks if the left value is less than or equal to the right value.
$a -le $bOperator -like (Contains Wildcard)
Comparison operator that uses wildcards like `*` and `?` to find patterns in strings. Returns `$true` if string `$a` contains "text".
$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.
$a -match "regex"Operator -and (Logical AND)
Logical operator that returns `$true` if both expressions `$a` and `$b` are true. Otherwise, returns `$false`.
$a -and $bOperator -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.
$a -or $bOperator -not (Negation)
Logical operator that inverts the boolean value of an expression. If `$a` is `$true`, `-not $a` will be `$false`, and vice-versa.
-not $aOperator -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.
$a -xor $bSelect-Object (Properties)
Selects specific properties of objects in the pipeline. In this example, it displays only the name, CPU, and memory of each process.
Get-Process | Select-Object Name, CPU, MemorySelect-Object -First
Selects only the first `N` objects from the pipeline. Useful for limiting output or getting data samples.
Get-Process | Select-Object -First 10Select-Object -Last
Selects only the last `N` objects from the pipeline. Useful for viewing the most recent or final items in a list.
Get-Process | Select-Object -Last 5Select-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.
Get-Process | Select-Object -Unique⚙️ Process Management
14 snippetsCommands 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.
Get-ProcessGet-Process (Specific)
Gets information about processes with a specific name. Wildcards can be used, such as `"chrome*"` for all processes starting with "chrome".
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.
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.
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10Start-Process (No Parameters)
Starts a new process on the system. In this example, it opens Notepad.
Start-Process notepad.exeStart-Process (With Parameter)
Starts a process and passes arguments to it. Here, Chrome is opened and navigates directly to google.com.
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.
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.
Stop-Process -Id 1234Stop-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.
Stop-Process -Name "chrome" -ForceGet-Service (All)
Lists all services installed on the system, including their current status (running, stopped) and display name.
Get-ServiceGet-Service (Specific)
Gets information about a specific service by its name. Useful for checking the status or properties of an individual service.
Get-Service -Name "Spooler"Start-Service
Starts a stopped service. The "Spooler" service is the Windows Print Spooler service.
Start-Service -Name "Spooler"Stop-Service
Stops a running service. By default, it will prompt for confirmation. Use `-Force` to force the stop.
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.
Restart-Service -Name "Spooler"🌐 Network and Connectivity
13 snippetsCommands 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.
Get-NetAdapterGet-NetIPAddress
Displays the IP addresses (IPv4 and IPv6) configured on each network adapter, along with the subnet prefix and default gateway.
Get-NetIPAddressGet-NetRoute
Displays the system's IP routing table, showing how network traffic is directed to different destinations.
Get-NetRouteTest-Connection
Sends ICMP (ping) packets to a remote host to check network connectivity. Returns details about response time and connection status.
Test-Connection google.comTest-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).
Test-NetConnection google.com -Port 80New-NetIPAddress
Configures a new static IP address on a network adapter. `-InterfaceAlias` specifies the adapter, `-IPAddress` the address, and `-PrefixLength` the subnet mask.
New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress 192.168.1.100 -PrefixLength 24Set-DnsClientServerAddress
Sets the DNS server addresses for a specific network adapter. In this example, it configures the primary DNS to Google's public DNS.
Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses 8.8.8.8Get-NetFirewallRule
Lists all Windows Defender Firewall rules, including inbound and outbound rules, affected programs, and ports.
Get-NetFirewallRuleNew-NetFirewallRule
Creates a new firewall rule. This example creates an inbound rule to allow RDP connections (TCP port 3389).
New-NetFirewallRule -DisplayName "Permitir RDP" -Direction Inbound -Protocol TCP -LocalPort 3389 -Action AllowInvoke-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.
Invoke-WebRequest https://api.example.comInvoke-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.
Invoke-RestMethod https://api.example.com/dataInvoke-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.
$response = Invoke-WebRequest https://example.com
$response.ContentInvoke-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.
Invoke-WebRequest https://example.com -OutFile "pagina.html"👥 Active Directory
13 snippetsCommands 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.
Get-ADUser -Filter *Get-ADUser (Specific)
Gets detailed information about a specific Active Directory user, using their SamAccountName, DistinguishedName, SID, or GUID.
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.
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.
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.
Disable-ADAccount -Identity "joao.silva"Get-ADGroup (All)
Lists all group objects in Active Directory. The `*` filter indicates that all groups should be returned.
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.
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.
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.
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.
Search-ADAccount -AccountDisabledGet-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.
Get-ADUser -Filter {PasswordNeverExpires -eq $true} -Properties PasswordNeverExpiresGet-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.
Get-ADUser -Filter {LastLogonDate -lt (Get-Date).AddDays(-90)} -Properties LastLogonDateExport 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.
Get-ADUser -Filter * -Properties * | Export-Csv "usuarios.csv" -NoTypeInformation🔒 Security and Permissions
10 snippetsManaging 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`.
Get-ExecutionPolicySet-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.
Set-ExecutionPolicy RemoteSignedSet-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.
Set-ExecutionPolicy -Scope Process -ExecutionPolicy BypassSet-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.
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy AllSignedGet-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.
Get-ChildItem Cert:\CurrentUser\MyGet-AuthenticodeSignature
Verifies the Authenticode digital signature of a file, such as a PowerShell script. Returns information about the signature status, signatory, and timestamp.
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:\...`.
Set-AuthenticodeSignature -FilePath "script.ps1" -Certificate $certGet-Acl (Folder Permissions)
Displays the Access Control Lists (ACLs), or security permissions, of a file or directory. Shows owner, group, and access rules.
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.
$acl = Get-Acl "C:\pasta"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Usuario","FullControl","Allow")
$acl.SetAccessRule($accessRule)
Set-Acl "C:\pasta" $aclGet-Acl (Detailed)
Displays file or folder permissions in a detailed list format, showing all Access Control Entries (ACEs) in a more readable way.
Get-Acl "arquivo.txt" | Format-List⏰ Automation and Scheduling
11 snippetsTechniques 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.
Get-ScheduledTaskRegister-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.
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.
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.
Disable-ScheduledTask -TaskName "MinhaTarefa"Unregister-ScheduledTask
Permanently removes a scheduled task from the system. The `-Confirm:$false` parameter prevents the confirmation prompt.
Unregister-ScheduledTask -TaskName "MinhaTarefa" -Confirm:$falseStart-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.
Start-Job -ScriptBlock { Get-Process } -Name "ProcessosJob"Get-Job
Lists all background jobs that are running or have completed in the current PowerShell session.
Get-JobReceive-Job
Retrieves the results of a background job. After retrieval, the results are removed from the job. Use `-Keep` to retain the results.
Receive-Job -Id 1Stop-Job
Terminates a running background job. It may be necessary to use `-Force` for unresponsive jobs.
Stop-Job -Id 1Remove-Job
Removes a background job from the current PowerShell session. This frees up resources associated with the job.
Remove-Job -Id 1Basic 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.
workflow MeuWorkflow {
parallel {
Get-Process
Get-Service
}
sequence {
Write-Host "Concluído"
}
}🖥️ WMI and CIM
11 snippetsExploring 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.
Get-WmiObject -Class Win32_OperatingSystemGet-WmiObject (Hardware Info)
Queries WMI to get general information about the computer system, including manufacturer name, model, domain name, and total physical memory.
Get-WmiObject -Class Win32_ComputerSystemGet-WmiObject (CPU Info)
Queries WMI to get details about the system's processor(s), such as manufacturer, speed, number of cores, and architecture.
Get-WmiObject -Class Win32_ProcessorGet-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.
Get-WmiObject -Class Win32_LogicalDiskGet-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`.
Get-CimInstance -ClassName Win32_OperatingSystemGet-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".
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.
New-CimSession -ComputerName servidorGet-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.
Get-CimInstance -CimSession $session -ClassName Win32_ServiceGet-EventLog (Latest Events)
Retrieves the 10 most recent events from the system event log. Useful for a quick check of recent events.
Get-EventLog -LogName System -Newest 10Get-WinEvent (Error Events)
A more advanced cmdlet for accessing event logs. This example filters Application log events with an error level (Level 2).
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.
Get-Counter "\Processor(_Total)\% Processor Time"Related cheatsheets
git status -sGit: The Emergency Kit
Messed up the code? Save this guide. Essential commands to undo mistakes, revert commits and save your job.
docker --versionDocker: Production Commands
Forget manual configuration. Copy and paste commands to spin up containers, clean volumes and deploy in record time.
ping -c 4 google.comLinux Networking: The Hacker Guide
Feel like Mr. Robot. Network commands to discover IPs, open ports and diagnose connections like a CyberSec professional.