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-LocationGUIs are for amateurs. Master the One-Liners and Pipelines that manage 100 servers simultaneously. Stop clicking windows and start treating your infrastructure as code.
Fundamentals for starting and interacting with the PowerShell environment, including file system navigation, getting essential information, and accessing documentation.
Displays the full path of the current working directory, functioning like the `pwd` (print working directory) command in Unix/Linux-based systems.
Get-LocationChanges 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:\UsersLists 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-ChildItemLists files and directories, including hidden and system items that are normally omitted. The `-Force` parameter is crucial for revealing these items.
Get-ChildItem -ForceLists files and directories recursively, traversing all subdirectories from the specified path. Useful for exploring the complete structure of a folder.
Get-ChildItem -RecurseCollects and displays detailed information about the operating system and local computer hardware, such as OS version, manufacturer, model, RAM, and processor.
Get-ComputerInfoLists all running processes on the system, providing details such as process ID (PID), name, CPU and memory usage. Essential for monitoring and diagnosis.
Get-ProcessDisplays a list of all installed services on the system, showing their status (running, stopped, etc.) and display name. Fundamental for service management.
Get-ServiceRetrieves 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 ApplicationLists all installed updates (hotfixes) on the Windows operating system, including the update ID, who installed it, and the installation date.
Get-HotFixProvides 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-ProcessDisplays information about cmdlets, functions, aliases, and scripts available in PowerShell. Useful for discovering commands and understanding their parameters.
Get-Command Get-ProcessDownloads and installs the latest help files for PowerShell modules. It is recommended to run this command regularly to access updated documentation.
Update-HelpLists all PowerShell modules that are available on the system, including those not yet loaded into the current session.
Get-Module -ListAvailableEssential commands for creating, removing, copying, moving, renaming, and manipulating file and directory contents.
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 FileCreates a new directory (folder) at the specified path. The `-ItemType Directory` parameter indicates that a directory should be created.
New-Item -Path "pasta" -ItemType DirectoryDeletes a specific file. By default, it will prompt for confirmation before removing the item.
Remove-Item "arquivo.txt"Deletes a directory and all its contents (subdirectories and files). The `-Recurse` parameter is mandatory to remove non-empty directories.
Remove-Item "pasta" -RecurseForces 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" -ForceCopies 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"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" -RecurseMoves 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"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"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"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 10Writes 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"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"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"How to declare variables, manipulate different data types like strings, integers, booleans, and use collection structures like arrays and hash tables.
Declares a variable `$nome` and assigns it a string (text) value. Variables in PowerShell start with `$`.
$nome = "João"Declares a variable `$idade` and assigns it an integer (whole number) value.
$idade = 25Declares a variable `$altura` and assigns it a decimal (number with decimal places) value.
$altura = 1.75Declares a variable `$ativo` and assigns it a boolean value, which can be `$true` (true) or `$false` (false).
$ativo = $trueDeclares a variable `$dados` and assigns it the value `$null`, indicating the absence of a value or object.
$dados = $nullCreates an array (ordered list) of strings. The `@()` operator is used to define an array literal.
$lista = @("item1", "item2", "item3")Creates an array of integers from 1 to 10 using the range operator (`..`).
$numeros = 1..10Accesses a specific element of an array using its index (position). PowerShell uses zero-based indexing, so `[0]` accesses the first element.
$lista[0]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]Returns the number of elements (size) of an array using the `.Count` property.
$lista.CountAdds 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"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}Accesses the value associated with a key in a hashtable using dot notation, if the key is a valid property name.
$pessoa.NomeAccesses 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"]Adds a new key-value pair to an existing hashtable or updates the value of an existing key.
$pessoa.Cidade = "São Paulo"Returns a collection of all keys present in the hashtable.
$pessoa.KeysReturns a collection of all values present in the hashtable.
$pessoa.ValuesCommands for controlling script execution flow, enabling conditional decisions and code block repetition.
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"}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"}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}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}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}Executes a block of code repeatedly as long as a specified condition is true. The condition is evaluated before each iteration.
$contador = 0while ($contador -lt 5) { Write-Host $contador $contador++}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")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" }}Creating and using functions to modularize code, define advanced parameters, and organize scripts into reusable modules.
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!"}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}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}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}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"}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.ps1Loads 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.psm1Specifies 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 MinhaFuncaoAn automatic variable that displays details about the PowerShell version, edition, .NET Framework version, and other runtime environment information.
$PSVersionTableLeverage the power of PowerShell pipeline to chain commands and use comparison and logical operators to filter and manipulate data efficiently.
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}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"}Gets all services and filters them to show only those whose status (`$_.Status`) is "Running".
Get-Service | Where-Object {$_.Status -eq "Running"}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 -DescendingComparison operator that checks if two values are equal. Returns `$true` if they are equal, `$false` otherwise.
$a -eq $bComparison operator that checks if two values are different. Returns `$true` if they are different, `$false` otherwise.
$a -ne $bComparison operator that checks if the left value is strictly greater than the right value.
$a -gt $bComparison operator that checks if the left value is greater than or equal to the right value.
$a -ge $bComparison operator that checks if the left value is strictly less than the right value.
$a -lt $bComparison operator that checks if the left value is less than or equal to the right value.
$a -le $bComparison operator that uses wildcards like `*` and `?` to find patterns in strings. Returns `$true` if string `$a` contains "text".
$a -like "*texto*"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"Logical operator that returns `$true` if both expressions `$a` and `$b` are true. Otherwise, returns `$false`.
$a -and $bLogical operator that returns `$true` if at least one of expressions `$a` or `$b` is true. Returns `$false` only if both are false.
$a -or $bLogical operator that inverts the boolean value of an expression. If `$a` is `$true`, `-not $a` will be `$false`, and vice-versa.
-not $aLogical 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 $bSelects 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, MemorySelects only the first `N` objects from the pipeline. Useful for limiting output or getting data samples.
Get-Process | Select-Object -First 10Selects 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 5Removes 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 -UniqueCommands for listing, monitoring, starting, and terminating processes and services on Windows, essential for administration and troubleshooting.
Lists all processes currently running on the system, providing information such as ID, name, CPU, and memory usage.
Get-ProcessGets information about processes with a specific name. Wildcards can be used, such as `"chrome*"` for all processes starting with "chrome".
Get-Process -Name "chrome"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}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 10Starts a new process on the system. In this example, it opens Notepad.
Start-Process notepad.exeStarts a process and passes arguments to it. Here, Chrome is opened and navigates directly to google.com.
Start-Process chrome.exe "https://google.com"Terminates a process with a specific name. By default, it will prompt for confirmation. Use `-Force` to force termination.
Stop-Process -Name "notepad"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 1234Forces 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" -ForceLists all services installed on the system, including their current status (running, stopped) and display name.
Get-ServiceGets information about a specific service by its name. Useful for checking the status or properties of an individual service.
Get-Service -Name "Spooler"Starts a stopped service. The "Spooler" service is the Windows Print Spooler service.
Start-Service -Name "Spooler"Stops a running service. By default, it will prompt for confirmation. Use `-Force` to force the stop.
Stop-Service -Name "Spooler"Restarts a service, first stopping it and then starting it again. Useful for applying configurations or resolving temporary issues.
Restart-Service -Name "Spooler"Commands for diagnosing, configuring, and interacting with the network, including adapters, IP addresses, firewall, and HTTP/REST requests.
Lists all network adapters installed on the system, providing information such as name, status, speed, and media type.
Get-NetAdapterDisplays the IP addresses (IPv4 and IPv6) configured on each network adapter, along with the subnet prefix and default gateway.
Get-NetIPAddressDisplays the system's IP routing table, showing how network traffic is directed to different destinations.
Get-NetRouteSends ICMP (ping) packets to a remote host to check network connectivity. Returns details about response time and connection status.
Test-Connection google.comTests 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 80Configures 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 24Sets 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.8Lists all Windows Defender Firewall rules, including inbound and outbound rules, affected programs, and ports.
Get-NetFirewallRuleCreates 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 AllowSends 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.comSends 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/dataPerforms 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.ContentDownloads 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"Commands for managing users, groups, and performing advanced Active Directory queries, essential for domain administrators and IT automation.
Lists all user objects in Active Directory. The `*` filter indicates that all users should be returned.
Get-ADUser -Filter *Gets detailed information about a specific Active Directory user, using their SamAccountName, DistinguishedName, SID, or GUID.
Get-ADUser -Identity "joao.silva"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"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"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"Lists all group objects in Active Directory. The `*` filter indicates that all groups should be returned.
Get-ADGroup -Filter *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"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"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"Searches for accounts in Active Directory based on specific criteria. `-AccountDisabled` returns all user accounts that are disabled.
Search-ADAccount -AccountDisabledFilters 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 PasswordNeverExpiresFilters 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 LastLogonDateExports 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" -NoTypeInformationManaging script execution policies, code signing, and file access control, ensuring PowerShell environment security and integrity.
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-ExecutionPolicySets 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 RemoteSignedSets 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 BypassSets 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 AllSignedLists all digital certificates installed in the current user's "Personal" (My) store. Useful for checking available certificates for code signing.
Get-ChildItem Cert:\CurrentUser\MyVerifies 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"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 $certDisplays the Access Control Lists (ACLs), or security permissions, of a file or directory. Shows owner, group, and access rules.
Get-Acl "C:\pasta"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" $aclDisplays 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-ListTechniques for automating repetitive tasks, scheduling script execution, and managing background jobs to optimize operational efficiency.
Lists all scheduled tasks configured on the Windows operating system, including their status, name, and next run time.
Get-ScheduledTaskCreates 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."Starts the execution of a scheduled task manually, regardless of its programmed trigger.
Start-ScheduledTask -TaskName "MinhaTarefa"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"Permanently removes a scheduled task from the system. The `-Confirm:$false` parameter prevents the confirmation prompt.
Unregister-ScheduledTask -TaskName "MinhaTarefa" -Confirm:$falseStarts 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"Lists all background jobs that are running or have completed in the current PowerShell session.
Get-JobRetrieves the results of a background job. After retrieval, the results are removed from the job. Use `-Keep` to retain the results.
Receive-Job -Id 1Terminates a running background job. It may be necessary to use `-Force` for unresponsive jobs.
Stop-Job -Id 1Removes a background job from the current PowerShell session. This frees up resources associated with the job.
Remove-Job -Id 1Defines 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" }}Exploring and manipulating Windows system information using WMI and CIM for advanced monitoring, inventory, and diagnostics.
Queries WMI to get detailed information about the Windows operating system, such as version, service pack, installation date, and manufacturer.
Get-WmiObject -Class Win32_OperatingSystemQueries WMI to get general information about the computer system, including manufacturer name, model, domain name, and total physical memory.
Get-WmiObject -Class Win32_ComputerSystemQueries WMI to get details about the system's processor(s), such as manufacturer, speed, number of cores, and architecture.
Get-WmiObject -Class Win32_ProcessorQueries 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_LogicalDiskModern 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_OperatingSystemExecutes 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'"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 servidorExecutes 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_ServiceRetrieves the 10 most recent events from the system event log. Useful for a quick check of recent events.
Get-EventLog -LogName System -Newest 10A 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}Gets data from system performance counters. This example monitors total processor utilization time in real-time.
Get-Counter "\Processor(_Total)\% Processor Time"