acm perfect
acm perfect
acm perfect
powershell Pipeline
1. Definition: A PowerShell pipeline (|) allows you to pass the output of one command as input to
another command.
2. Symbol: The pipeline operator is represented by the vertical bar (|).
3. Object-based: Unlike traditional shells (which use text), PowerShell pipelines pass objects, enabling
more complex and accurate data manipulation.
4. Chaining: You can chain multiple commands together to perform sequential processing, e.g., Get-
Process | Sort-Object CPU | Select-Object -First 5.
5. Efficiency: Pipelines process data as streams, reducing memory use by handling one object at a time.
6. Cmdlet Compatibility: Most PowerShell cmdlets are designed to work seamlessly in pipelines.
7. Syntax Simplicity: Easy to write and read, making complex tasks manageable in fewer lines of code.
8. Examples:
o List files by size: Get-ChildItem | Sort-Object Length
o Find and stop a process: Get-Process | Where-Object Name -eq "notepad" | Stop-Process
2.powershell Cmdlets
1. Definition: Cmdlets are small, built-in commands in PowerShell used to perform specific tasks.
2. Structure: Cmdlets follow the verb-noun naming convention, e.g., Get-Process, Set-Item.
3. Verb-Noun Logic: The verb describes the action (e.g., Get, Set, Remove), and the noun specifies the
object being acted upon (e.g., Process, Service).
4. Object-based: Cmdlets work with objects rather than plain text, enabling more precise and flexible
data handling.
5. Ease of Use: Cmdlets have a consistent syntax, making them easy to learn and use across different
tasks.
6. Parameter Support: Cmdlets accept parameters to customize their behavior, e.g., Get-Process -Name
notepad.
7. Built-in Help: Use Get-Help <cmdlet> to access detailed information and examples about any cmdlet.
8. Examples:
o Get system processes: Get-Process
o Create a directory: New-Item -Path "C:\NewFolder" -ItemType Directory
o Stop a service: Stop-Service -Name "wuauserv"
3.powershell Providers
1. Definition: PowerShell providers let you access and manage data stores (e.g., file system, registry) like
you would a file system.
2. Purpose: They provide a consistent way to navigate and manipulate different data stores using
common cmdlets like Get-ChildItem, Set-Item, etc.
3. Supported Stores: Examples include FileSystem, Registry, Environment variables, Certificate stores,
and more.
4. Navigation: You can use familiar commands (cd, dir, ls) to browse and interact with providers.
5. File System Example: Navigate directories: cd C:\, List files: Get-ChildItem C:\.
6. Registry Example: Access registry keys like folders: cd HKLM:\, List keys: Get-ChildItem HKLM:\
Software.
7. Cmdlets Compatibility: Cmdlets like Get-ChildItem, Set-Item, and Remove-Item work across all
providers.
8. View Providers: Use Get-PSProvider to see all available providers on your system.
4.powershell WMI
1. Definition: WMI is a Windows feature that provides a way to query and manage system information,
such as hardware, software, and system settings.
2. Purpose: It is used for system administration tasks like retrieving system details, managing processes,
and automating tasks.
3. Cmdlets: PowerShell uses cmdlets like Get-WmiObject (older) and Get-CimInstance (newer and
recommended) to interact with WMI.
4. Namespace: WMI organizes data in namespaces (e.g., root\cimv2), where most system management
classes are located.
5. WMI Classes: Classes like Win32_OperatingSystem or Win32_Process provide specific types of system
data.
6. Examples:
o Get OS info: Get-CimInstance -ClassName Win32_OperatingSystem
o List running processes: Get-CimInstance -ClassName Win32_Process
7. Automation: WMI allows automation of system management tasks, such as stopping a process or
modifying configurations.
8. Cross-Network Use: WMI can query and manage remote systems if proper permissions are set up.
5.powershell Scripts
1. Definition: A PowerShell script is a collection of PowerShell commands saved in a .ps1 file that can be
executed as a single program.
2. Purpose: Scripts automate repetitive tasks and can be used to configure, manage, and troubleshoot
systems.
3. Syntax: PowerShell scripts use cmdlets, variables, loops, and conditional statements to perform tasks.
4. File Extension: PowerShell scripts are saved with the .ps1 extension, e.g., myscript.ps1.
5. Execution: To run a script, you type its path in the PowerShell console, e.g., .\myscript.ps1.
6. Variables: You can define variables in scripts, such as $name = "User", to store and manipulate data.
7. Control Flow: PowerShell scripts can use control structures like if, for, and while to handle logic and
loops.
8. Examples:
o Create a file: New-Item -Path "C:\TestFile.txt" -ItemType File
o Loop through processes:
$processes = Get-Process
foreach ($process in $processes) {
Write-Output $process.Name
}
6.powershell Errors
1. Definition: PowerShell errors occur when something goes wrong while executing a command or script,
such as incorrect syntax or missing resources.
2. Error Types: There are two main types of errors:
o Terminating errors: Stop the script and return control to the user.
o Non-terminating errors: Do not stop the script, but report a problem.
3. Common Cmdlets: Cmdlets like Try, Catch, and Finally handle errors in scripts to manage them
effectively.
4. Error Variable: $Error stores a list of recent errors, where the most recent error is $Error[0].
5. ErrorAction: The -ErrorAction parameter allows you to control how errors are handled, e.g., Stop,
SilentlyContinue, Continue, etc.
6. Viewing Errors: Use Get-Error to display detailed information about an error, including its type and
message.
7. Throwing Errors: You can use the throw keyword to manually generate an error in a script, e.g., throw
"Custom error message".
8. Examples:
o Catch an error:
try {
Get-Process -Name "NonExistentProcess"
} catch {
Write-Host "Error: $_"
}
Use -ErrorAction:
Get-Process -Name "NonExistentProcess" -ErrorAction SilentlyContinue
7.powershell Remoting
1. Definition: PowerShell Remoting allows you to run commands and scripts on remote computers over
a network.
2. Protocols: It uses protocols like WS-Management (HTTP/S) or SSH to communicate with remote
systems.
3. Enable Remoting: To use remoting, you must first enable it on both the local and remote machines
using the Enable-PSRemoting cmdlet.
4. Cmdlets: Key remoting cmdlets include Enter-PSSession (for interactive sessions) and Invoke-
Command (for running scripts on remote machines).
5. Authentication: Remoting requires proper credentials, either through Windows authentication or
user-defined credentials.
6. Remote Sessions: You can create remote sessions using New-PSSession and use them for multiple
commands without re-authenticating.
7. Examples:
o Start a remote session: Enter-PSSession -ComputerName RemotePC
o Run a command remotely: Invoke-Command -ComputerName RemotePC -ScriptBlock { Get-
Process }
8. Security: PowerShell Remoting uses encryption and supports secure configurations like HTTPS for safe
communication.
8.powershell Implicit
1. Definition: In PowerShell, implicit refers to automatic actions or behaviors that PowerShell does
without explicit instructions from the user.
2. Implicit Variables: PowerShell automatically creates some variables for you, like $null, $true, and
$false.
3. Implicit Casting: PowerShell can automatically convert (cast) data types when necessary. For example,
if you add an integer and a string, PowerShell will try to convert the integer to a string.
4. Implicit Pipeline: PowerShell automatically passes output from one cmdlet to the next in a pipeline,
even if you don't explicitly define how.
5. Implicit Scope: Variables in PowerShell, by default, are created in the local scope, meaning they are
available in the current script or session without explicit scope declaration.
6. Implicit Module Loading: PowerShell automatically loads modules when cmdlets or functions from
them are used for the first time, without needing a Import-Module command.
7. Implicit Execution Policy: By default, PowerShell may allow the execution of signed scripts, but may
restrict unsigned ones, depending on the execution policy set in the environment.
8. Examples:
o Implicitly adding values: $a = 5; $b = "Test"; $c = $a + $b results in $c being "5Test".
o Using implicit pipeline: Get-Process | Where-Object { $_.CPU -gt 100 } automatically passes
the Get-Process output to Where-Object.
9.powershell Jobs
1. Definition: PowerShell jobs allow you to run commands or scripts in the background without blocking
the rest of your session.
2. Types of Jobs: There are two main types:
o Background Jobs: Run asynchronously in the background.
o Remote Jobs: Run on remote computers using PowerShell Remoting.
3. Job Cmdlets: Key cmdlets for managing jobs include:
o Start-Job to initiate a background job.
o Get-Job to view job status and details.
o Stop-Job to stop a running job.
o Receive-Job to get the results from a completed job.
4. Job Output: Output from jobs is saved and can be retrieved later using Receive-Job or by checking the
job's status.
5. Job States: Jobs can be in various states like Running, Completed, or Failed.
6. Examples:
o Start a background job: Start-Job -ScriptBlock { Get-Process }
o View job status: Get-Job
o Retrieve results: Receive-Job -Id 1
7. Job Cleanup: After finishing, use Remove-Job to clean up completed or failed jobs.
8. Job Limitations: Jobs run in their own session, so variables and functions defined in the main session
are not directly available to jobs.
10 powershell Schedules
1. Definition: PowerShell scheduling allows you to run scripts or commands at specified times or
intervals automatically.
2. Task Scheduler: PowerShell integrates with Windows Task Scheduler, allowing you to create and
manage scheduled tasks from the command line.
3. Cmdlets for Scheduling: Key cmdlets include New-ScheduledTask, Register-ScheduledTask, and Get-
ScheduledTask for managing tasks.
4. Trigger: A trigger defines when a scheduled task will run, such as daily, weekly, or at a specific time.
5. Action: The action specifies what the task will do, such as running a PowerShell script or command.
6. Examples:
o Create a simple scheduled task:
$action = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "C:\Path\To\Script.ps1"
$trigger = New-ScheduledTaskTrigger -At 9AM -Daily
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "MyTask"
7. Task Settings: You can specify task settings like whether to run the task if the computer is on battery,
or if the task should run even if the user is not logged in.
8. Viewing Scheduled Tasks: Use Get-ScheduledTask to list existing tasks and check their status.
11.powershell Profiles
1. Definition: A PowerShell profile is a script file that runs automatically when you start a new
PowerShell session, allowing you to customize your environment.
2. Purpose: Profiles are used to define custom variables, functions, aliases, or settings that should be
available every time you open PowerShell.
3. Profile File Locations: PowerShell has several profile files depending on the context:
o All Users, All Hosts: Affects all users and all PowerShell hosts ($PROFILE.AllUsersAllHosts).
o All Users, Current Host: Affects all users for the current host ($PROFILE.AllUsersCurrentHost).
o Current User, All Hosts: Affects the current user across all hosts
($PROFILE.CurrentUserAllHosts).
o Current User, Current Host: Affects the current user for the current host ($PROFILE).
4. Customization: You can add custom aliases, functions, or import modules in your profile to enhance
productivity. For example:
Set-Alias ll Get-ChildItem
5. Accessing Profiles: To view or edit your profile, you can use the $PROFILE variable, e.g., notepad.exe
$PROFILE.
6. Creating a Profile: If a profile file doesn't exist, you can create one using:
New-Item -Path $PROFILE -ItemType File -Force
7. Security: Be cautious about adding commands to profiles, as they are executed automatically and
could potentially impact your environment.
8. Examples:
o Add custom functions to the profile:
function Get-MyFiles {
Get-ChildItem -Path "C:\Users\$env:USERNAME\Documents"
}
12.powershell Validation
1. Definition: PowerShell validation ensures that input parameters for cmdlets, functions, or scripts meet
specific criteria before execution.
2. Purpose: It is used to enforce rules, ensuring that users provide valid and expected data (e.g., correct
data type, range, or format).
3. Parameter Validation: Validation is typically applied to function or script parameters using validation
attributes like ValidateRange, ValidatePattern, and ValidateSet.
4. Common Validation Attributes:
o ValidateRange: Ensures the value is within a specified range.
param (
[ValidateRange(1, 10)]
[int]$number
)
o ValidatePattern: Ensures the value matches a regular expression pattern.
param (
[ValidatePattern("^\d{3}-\d{2}-\d{4}$")]
[string]$ssn
)
5. ValidateSet: Restricts input to a set of valid values.
param (
[ValidateSet("Yes", "No")]
[string]$confirmation
)
6. ValidateNotNullOrEmpty: Ensures the parameter is not null or empty.
param (
[ValidateNotNullOrEmpty()]
[string]$username
)
7. Error Handling: If validation fails, PowerShell throws an error and prevents the script or cmdlet from
running with invalid input.
13.powershell Network
1. Definition: PowerShell Network cmdlets allow you to manage and troubleshoot network-related tasks,
such as checking connectivity, configuring IP settings, and managing network adapters.
2. Testing Connectivity: You can test network connectivity using the Test-Connection cmdlet, similar to
the ping command.
Test-Connection -ComputerName google.com
3. Getting Network Adapter Info: The Get-NetAdapter cmdlet retrieves information about network
adapters on the system.
Get-NetAdapter
4. Configuring IP Address: Use New-NetIPAddress to configure a static IP address for a network adapter.
New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress "192.168.1.10" -PrefixLength 24 -DefaultGateway
"192.168.1.1"
5. Viewing Network Configuration: Get-NetIPConfiguration provides detailed network configuration,
including IP address, subnet mask, and DNS servers.
Get-NetIPConfiguration
6. Managing DNS Settings: Set-DnsClientServerAddress allows you to configure DNS server addresses for
a network adapter.
Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses "8.8.8.8", "8.8.4.4"
7. Checking Active Connections: Get-NetTCPConnection shows active TCP connections and their states.
Get-NetTCPConnection
8. Network Shares: Use New-SmbShare to create a network share and share files over the network.
New-SmbShare -Name "MyShare" -Path "C:\SharedFolder" -FullAccess "Everyone"
14.powershell Sorting
1. Definition: PowerShell sorting is used to reorder objects, such as numbers or strings, in ascending or
descending order.
2. Sorting Cmdlet: The primary cmdlet for sorting is Sort-Object.
3. Basic Usage: To sort a list of objects (like numbers or strings), use Sort-Object with the input.
5, 3, 8, 1 | Sort-Object
4. Sorting by Property: You can sort objects by a specific property, such as sorting processes by memory
usage.
Get-Process | Sort-Object -Property CPU
5. Descending Order: To sort in descending order, use the -Descending parameter.
5, 3, 8, 1 | Sort-Object -Descending
6. Sorting Multiple Properties: You can sort by more than one property. For example, sort by age and
then name.
$users = @(
[PSCustomObject]@{Name="John"; Age=30}
[PSCustomObject]@{Name="Jane"; Age=25}
[PSCustomObject]@{Name="Bob"; Age=25}
)
$users | Sort-Object -Property Age, Name
7. Sorting Strings: PowerShell sorts strings alphabetically by default.
"apple", "banana", "cherry" | Sort-Object
8. Handling Null Values: When sorting, null values are treated as the lowest value in ascending order.
$array = 3, $null, 1
$array | Sort-Object
15.powershell HashTables
1. Definition: A HashTable is a collection of key-value pairs, where each key is unique and maps to a
specific value.
2. Creating a HashTable: You can create a HashTable using @{} notation.
$hashtable = @{Key1="Value1"; Key2="Value2"}
3. Accessing Values: Use the key to access the corresponding value in the HashTable.
$hashtable["Key1"] # Output: Value1
4. Adding Items: You can add new key-value pairs to a HashTable.
$hashtable["Key3"] = "Value3"
5. Removing Items: Use the Remove method to remove a key-value pair.
$hashtable.Remove("Key2")
6. Checking for Key: You can check if a key exists in the HashTable with the ContainsKey method.
$hashtable.ContainsKey("Key1") # Output: True
7. Listing Keys and Values: You can list all the keys or values using Keys and Values properties.
$hashtable.Keys # Output: Key1, Key3
$hashtable.Values # Output: Value1, Value3
8. Example: Create a HashTable for storing user details.
$userDetails = @{
Name = "John"
Age = 30
City = "New York"
}
$userDetails["Name"] # Output: John
4o mini