0% found this document useful (0 votes)
40 views14 pages

acm done

Uploaded by

badeaniket57
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views14 pages

acm done

Uploaded by

badeaniket57
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Pipeline

Definition: The pipeline (|) allows you to pass the output of one command directly as input to another.
1. Command Chaining: Commands in the pipeline are executed sequentially. Each command receives input from the
previous one and sends output to the next.
2. Objects, Not Text: Unlike traditional pipelines that pass text, passes objects through the pipeline, maintaining
their properties and methods.
3. Efficiency: The pipeline allows you to perform complex tasks by combining small, reusable commands, making
scripts more efficient and readable.
4. Cmdlet Example:
Get-Process | Where-Object {$_.CPU -gt 100}
This retrieves processes and filters them based on CPU usage.
5. Select-Object: You can use the pipeline to select specific properties of an object.
Get-Process | Select-Object Name, CPU
6. Filtering: Use Where-Object to filter objects passing through the pipeline based on conditions.
7. Custom Functions: You can write custom functions to process pipeline input, giving you flexibility in data
handling.
Active Directory Cmdlets
Definition: Active Directory cmdlets are built-in commands used to manage Active Directory (AD) objects like users,
groups, and computers.
1. Module: The cmdlets are part of the ActiveDirectory module, which needs to be imported before use:

Import-Module ActiveDirectory
2. Get-ADUser: Used to retrieve user accounts from Active Directory.
Get-ADUser -Identity username
3. New-ADUser: Creates a new user account in Active Directory.
New-ADUser -Name "John Doe" -SamAccountName "jdoe" -UserPrincipalName "jdoe@domain.com"
4. Set-ADUser: Modifies properties of an existing user account.
Set-ADUser -Identity username -Title "Manager"
5. Get-ADGroup: Retrieves information about AD groups.
Get-ADGroup -Identity "GroupName"
6. Add-ADGroupMember: Adds a user to an AD group.
Add-ADGroupMember -Identity "GroupName" -Members "username"
7. Remove-ADUser: Deletes a user account from Active Directory.
Remove-ADUser -Identity username
PSProviders and PSDrives
PSProvider: A PSProvider is a .NET class in that allows access to different data stores (like the file system, registry, or
environment variables) as if they were file systems.
1. PSDrive: A PSDrive is a mapped drive that provides access to a data store (like a folder, registry key, or
environment variable) using a provider. It's like a virtual drive in .
2. Common Providers: Examples of built-in providers include:
o FileSystem: Access to the file system.
o Registry: Access to the Windows registry.
o Environment: Access to environment variables.
o Alias: Access to command aliases.
3. Viewing PSDrives: To see the currently available PSDrives, use:
Get-PSDrive
4. Creating a PSDrive: You can create a new PSDrive to access data stores, for example:
New-PSDrive -Name MyDrive -PSProvider FileSystem -Root "C:\Users"
5. Using PSDrives: Once a PSDrive is created, you can use it like any regular drive in :
Set-Location MyDrive:
6. Removing a PSDrive: To remove a PSDrive after use, you can delete it:
Remove-PSDrive -Name MyDrive
7. Scope of PSDrives: PSDrives can be created with different scopes, either temporary (for the current session) or
permanent (for all sessions), depending on the parameters used.
WMI and CIM
WMI: WMI is a Microsoft technology for managing and monitoring system resources, devices, and applications in Windows
environments.
1. CIM: CIM is a standard model used to describe objects in the management of hardware, software, and network
devices. CIM is a newer, more flexible approach compared to WMI.
2. WMI vs. CIM:
o WMI is based on COM (Component Object Model) and is specific to Windows.
o CIM is a newer, platform-independent standard based on WS-Man (Web Services Management) and
works across different operating systems.
3. Cmdlets for WMI: WMI cmdlets include Get-WmiObject, Set-WmiObject, and Invoke-WmiMethod for interacting
with WMI objects.
Get-WmiObject -Class Win32_OperatingSystem
4. Cmdlets for CIM: CIM cmdlets include Get-CimInstance, Set-CimInstance, and Invoke-CimMethod. CIM cmdlets
are part of the newer CIMCmdlets module and use the CIM standard.
Get-CimInstance -ClassName Win32_OperatingSystem
5. Performance: CIM is generally more efficient and faster than WMI because it uses the newer WS-Man protocol,
while WMI uses DCOM (Distributed COM), which can be slower and less reliable over networks.
6. Cross-Platform Support: CIM works better in cross-platform scenarios (e.g., remote management of non-
Windows systems) because it follows the CIM standard, which is more versatile across different operating
systems.
7. Compatibility: WMI and CIM are largely compatible in . You can use either, but CIM is recommended for newer
scripts due to its better performance and cross-platform capabilities.
Scripts
Definition: A script is a text file containing a series of commands or cmdlets. It automates repetitive tasks, system
administration, and other processes in Windows environments.
1. File Extension: scripts typically have the .ps1 extension (e.g., myscript.ps1).
2. Running Scripts: To run a script, use the .\ notation in :
.\myscript.ps1
3. Execution Policy: By default, Windows restricts script execution for security reasons. You may need to adjust the
execution policy to run scripts:
Set-ExecutionPolicy RemoteSigned
4. Variables: You can declare and use variables in scripts to store and manipulate data.
$name = "John Doe"
Write-Output $name
5. Loops and Conditionals: scripts support loops (e.g., for, foreach) and conditionals (e.g., if, else) to control flow
based on logic.
foreach ($item in $array) {
Write-Output $item
}
6. Functions: You can define reusable functions in scripts to group commands.
function Get-MyInfo {
Write-Output "Information"
}
7. Comments: Comments are added to scripts using # for single-line comments or <# #> for block comments,
helping document the script’s functionality.
# This is a comment
<#
This is a block comment
#>
Error Handling
Error Types: has two types of errors:
o Terminating errors: These stop script execution (e.g., missing files, permissions issues).
o Non-terminating errors: These don't stop the script (e.g., missing a value in a collection).
2. $Error Variable: stores error details in the $Error automatic variable. You can check the last error like this:
$Error[0]
3. Try, Catch, Finally: The try, catch, and finally blocks are used for handling terminating errors.
o Try: Code that may cause an error.
o Catch: Code that runs when an error occurs.
o Finally: Code that runs regardless of success or failure.
$ErrorActionPreference = "Stop"
4. -ErrorAction Parameter: You can override $ErrorActionPreference for specific cmdlets using the -ErrorAction
parameter.
Get-Content "missingfile.txt" -ErrorAction SilentlyContinue
5. $null for Error Handling: Sometimes you want to handle errors without stopping the script. You can suppress
errors by redirecting them to $null.
Get-Content "missingfile.txt" 2>$null
6. Throwing Errors: You can manually generate errors in a script using the throw keyword. This will cause a
terminating error.
throw "This is a custom error"
7. Logging Errors: You can log errors to a file for later review.

Remoting
Definition: Remoting allows you to run commands on remote computers from your local machine, making it easier to
manage multiple systems.
1. Enable Remoting: Remoting is enabled by default on Windows Server but needs to be manually enabled on client
machines using the Enable-PSRemoting cmdlet:
Enable-PSRemoting -Force
2. Basic Syntax: To run a command remotely, use the Invoke-Command cmdlet:
Invoke-Command -ComputerName RemotePC -ScriptBlock { Get-Process }
3. Enter-PSSession: For an interactive session, use Enter-PSSession to open a remote session:
Enter-PSSession -ComputerName RemotePC
You can then run commands as if you were directly on the remote machine.
4. Exit-PSSession: To exit a remote session, use Exit-PSSession:
Exit-PSSession
5. Credentials: You can specify credentials when remoting by using the -Credential parameter:
$cred = Get-Credential
Invoke-Command -ComputerName RemotePC -Credential $cred -ScriptBlock { Get-Process }
6. Remote Session for Multiple Computers: To run a command on multiple remote computers, use Invoke-
Command with an array of computer names:
Invoke-Command -ComputerName RemotePC1, RemotePC2 -ScriptBlock { Get-Process }
7. Persistent Remote Sessions: Use New-PSSession to create a persistent session and Enter-PSSession or Invoke-
Command to interact with it:
$session = New-PSSession -ComputerName RemotePC
Invoke-Command -Session $session -ScriptBlock { Get-Process }
mplicit Remoting vs. PS-Sessions
1. Definition
 Implicit Remoting: Allows you to run commands on remote computers by importing cmdlets from a remote
session into your local session.
 Sessions (PS-Sessions): Establishes a persistent connection to a remote computer where you can run multiple
commands interactively.
2. Use Case
 Implicit Remoting: Best for using specific cmdlets or functions from a remote machine without interacting with
the remote machine directly.
 Sessions (PS-Sessions): Best for interacting with a remote machine over an extended period, running multiple
commands.
3. Setup
 Implicit Remoting: Requires importing cmdlets from the remote machine using Import-PSSession.
$session = New-PSSession -ComputerName RemotePC
Import-PSSession $session
 Sessions (PS-Sessions): You establish a session with New-PSSession and use Enter-PSSession to interact with it.
$session = New-PSSession -ComputerName RemotePC
Enter-PSSession $session
4. Cmdlet Availability
 Implicit Remoting: Only the cmdlets and functions from the remote machine are imported into your local session,
not the entire environment.
 Sessions (PS-Sessions): You have access to the full environment of the remote machine during the session.
5. Execution
 Implicit Remoting: You can run remote commands locally after importing the cmdlets; remote execution is
transparent.
Get-RemoteCommand
 Sessions (PS-Sessions): You directly execute commands on the remote machine, and the session remains open
until you close it.
Get-Process
6. Resource Usage
 Implicit Remoting: More efficient when you only need to use a few cmdlets from a remote machine since you
don’t need to maintain an interactive session.
 Sessions (PS-Sessions): Requires more resources, as the session stays open, and you are interacting with the full
remote environment.
7. Closing Connection
 Implicit Remoting: Ends when you remove the imported cmdlets or close the session using Remove-PSSession.
Remove-PSSession $session
 Sessions (PS-Sessions): Ends when you close the session with Exit-PSSession or Remove-PSSession.
Exit-PSSession
8. Use Across Multiple Systems
 Implicit Remoting: You can import cmdlets from several remote systems into your local session, giving you access
to cmdlets across multiple systems.
Import-PSSession $session1
Import-PSSession $session2
 Sessions (PS-Sessions): You can work with multiple remote sessions, but each session requires a separate
connection.
$session1 = New-PSSession -ComputerName RemotePC1
$session2 = New-PSSession -ComputerName RemotePC2

Background Jobs Scheduled Jobs


1. Definition
 Background Jobs: Allow you to run a task asynchronously in the background while you continue working in the
current session.
 Scheduled Jobs: Allow you to schedule tasks to run at specified times or intervals on a local or remote machine.
2. Initiation
 Background Jobs: Started using the Start-Job cmdlet. You can run any command or script in the background.
Start-Job -ScriptBlock { Get-Process }
 Scheduled Jobs: Created using the New-ScheduledJob cmdlet, specifying when and how often the job should run.
New-ScheduledJob -Name "GetProcessJob" -ScriptBlock { Get-Process } -Trigger (New-ScheduledJobTrigger -Daily -At
"8:00AM")
3. Execution
 Background Jobs: Runs immediately in the background of your current session.
 Scheduled Jobs: Executes automatically at the specified time or interval, even if is not open.
4. Management
 Background Jobs: Managed within the current session, and you can monitor or stop them using Get-Job and
Stop-Job.
Get-Job
Stop-Job -Name "Job1"
 Scheduled Jobs: Managed through the Task Scheduler, and can be listed or removed using Get-ScheduledJob and
Remove-ScheduledJob.
Get-ScheduledJob
Remove-ScheduledJob -Name "GetProcessJob"
5. Session Dependency
 Background Jobs: Tied to the current session. If the session is closed, the job is stopped.
 Scheduled Jobs: Independent of the current session. They can run even if is closed.
6. Use Case
 Background Jobs: Useful for running tasks concurrently in the same session, without blocking your work.
 Scheduled Jobs: Ideal for automating recurring tasks that need to run at specific times or intervals, like backups
or system checks.
7. Output Handling
 Background Jobs: You can retrieve the output of a background job using Receive-Job and store it in a variable.
$job = Start-Job -ScriptBlock { Get-Process }
$output = Receive-Job -Job $job
 Scheduled Jobs: Output is typically written to a log file or an event, and can be configured to send notifications.
8. Persistence
 Background Jobs: Jobs do not persist beyond the session, meaning they are lost when the session ends.
 Scheduled Jobs: Jobs persist and are stored in the Task Scheduler, so they can continue to run at the scheduled
times, even after rebooting or closing .

Profile Scripts
1. Definition
 Profile Scripts: profile scripts are special scripts that run automatically when starts. They allow you to configure
the environment and customize your session.
2. Location
 Profile scripts are located in specific files depending on the context. Common locations include:
o All Users (Machine): C:\Program Files\ \7\profile.ps1
o All Users (Current Session): C:\Windows\System32\Windows \v1.0\profile.ps1
o Current User (Current Session): ~\Documents\ \profile.ps1
o Current User (All Sessions): ~\Documents\ \profile.ps1
3. Types of Profiles
 All Users, All Hosts: Applies to all users, all hosts.
 All Users, Current Host: Applies to all users, but only for a specific host (like the console or VS Code).
 Current User, All Hosts: Applies to the current user for all hosts.
 Current User, Current Host: Applies to the current user and specific host.
4. Purpose
 Profile scripts allow you to set variables, functions, aliases, or import modules that should be available every time
you start .
5. Customizing Your Session
 You can add custom functions, cmdlets, or change the prompt appearance in your profile script. For example:
Set-PSReadlineOption -PredictionSource History
function Prompt { "MyCustomPrompt> " }
6. Conditional Execution
 You can use conditions to execute specific code only for certain users or environments.
if ($env:COMPUTERNAME -eq "Server1") {
Write-Host "Welcome to Server1"
}
7. Editing the Profile
 You can edit your profile script with a text editor. To open your profile script in , use:
notepad $PROFILE
8. Security Considerations
 By default, ’s execution policy may prevent scripts from running. You may need to change the policy to allow
profile scripts using:
Set-ExecutionPolicy RemoteSigned

Validating IP Address
1. Definition
 IP Address Validation: Involves checking if a given string is a valid IP address, either IPv4 (e.g., 192.168.1.1) or
IPv6 (e.g., 2001:0db8:85a3:0000:0000:8a2e:0370:7334).
2. Regular Expression (Regex)
 One common method for validating an IP address is using regular expressions to check the format.
o IPv4 Regex: Checks for 4 sets of numbers (0-255) separated by dots.
o IPv6 Regex: Checks for 8 groups of hexadecimal numbers separated by colons.
3. Example for IPv4 Validation
 You can use a regular expression in to validate an IPv4 address:
function Test-IPv4($ip) {
return $ip -match '^(\d{1,3}\.){3}\d{1,3}$' -and ($ip -split '\.') | ForEach-Object { [int]$_ -ge 0 -and [int]$_ -le 255 }
}
4. Example for IPv6 Validation
 You can use this regex to validate IPv6:
function Test-IPv6($ip) {
return $ip -match '^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$'
}
5. Built-in Cmdlet for Validation
 provides a built-in cmdlet, Test-Connection, which checks if an IP address is reachable but does not validate its
format.
Test-Connection -ComputerName 192.168.1.1
6. Using .NET Classes
 You can use the .NET System.Net.IPAddress class to validate IP addresses in :
function Test-ValidIPAddress($ip) {
[System.Net.IPAddress]::TryParse($ip, [ref]$null)
}
7. Validating Both IPv4 and IPv6
 You can combine checks for both IPv4 and IPv6 formats:
function Test-ValidIP($ip) {
if ([System.Net.IPAddress]::TryParse($ip, [ref]$null)) {
return $true
} else {
return $false
}
}
8. Handling Invalid Input
 If an invalid IP address is entered, you can handle the error with a message:
$ip = "192.999.1.1"
if (-not (Test-ValidIP $ip)) {
Write-Host "Invalid IP address"
}
Network Configuration Cmdlets
1. Get-NetAdapter
 Purpose: Displays the network adapters on a system, including their names, statuses, and types.
Get-NetAdapter
2. Set-NetAdapter
 Purpose: Allows you to configure settings for a network adapter, such as enabling or disabling it.
Set-NetAdapter -Name "Ethernet" -Enabled $false
3. Get-NetIPAddress
 Purpose: Retrieves IP address configurations (IPv4 and IPv6) for network adapters on the system.
Get-NetIPAddress
4. New-NetIPAddress
 Purpose: Assigns a new IP address to a network adapter. You can specify the IP address, subnet mask, and
gateway.
New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress "192.168.1.100" -PrefixLength 24 -DefaultGateway "192.168.1.1"
5. Set-NetIPAddress
 Purpose: Modifies an existing IP address configuration on a network adapter.
Set-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress "192.168.1.100" -PrefixLength 24
6. Get-NetRoute
 Purpose: Displays the routing table of the computer, showing how network traffic is routed.
Get-NetRoute
7. New-NetRoute
 Purpose: Adds a new route to the routing table, allowing you to define how traffic is routed to a specific
destination.
New-NetRoute -DestinationPrefix "10.0.0.0/24" -InterfaceAlias "Ethernet" -NextHop "192.168.1.1"
8. Get-NetDNSClient
 Purpose: Retrieves DNS client configurations for the system, including DNS servers and search domains.

Sorting and Filtering Objects


1. Filtering with Where-Object
 Purpose: Filters objects based on specified conditions. It allows you to narrow down results.
Get-Process | Where-Object {$_.CPU -gt 100}
This command filters processes where the CPU usage is greater than 100.
2. Sorting with Sort-Object
 Purpose: Sorts objects by specified properties. You can sort objects in ascending or descending order.
Get-Process | Sort-Object CPU
This command sorts processes by CPU usage in ascending order.
3. Sorting in Descending Order
 Purpose: You can sort objects in descending order using the -Descending flag.
Get-Process | Sort-Object CPU -Descending
This command sorts processes by CPU usage in descending order.
4. Filtering Multiple Conditions
 Purpose: You can filter based on multiple conditions using -and or -or.
Get-Process | Where-Object {$_.CPU -gt 100 -and $_.Name -eq "chrome"}
This filters processes where the CPU usage is greater than 100 and the process name is "chrome."
5. Selecting Specific Properties with Select-Object
 Purpose: You can select specific properties from objects after filtering or sorting.
Get-Process | Where-Object {$_.CPU -gt 100} | Select-Object Name, CPU
This command filters processes by CPU usage, then selects and displays only the Name and CPU properties.
6. Using -First and -Last
 Purpose: Retrieves the first or last few objects after sorting.
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5
This command retrieves the top 5 processes by CPU usage.
7. Filtering with Wildcards
 Purpose: Use wildcards to filter objects based on pattern matching.
Get-Process | Where-Object {$_.Name -like "chrome*"}
This command filters processes whose name starts with "chrome."
8. Combining Sorting and Filtering
 Purpose: You can combine sorting and filtering in a single pipeline for more complex queries.
Get-Process | Where-Object {$_.CPU -gt 50} | Sort-Object CPU -Descending
This command filters processes by CPU usage greater than 50, then sorts them in descending order by CPU.

Hash Tables in
1. Definition
 Hash Table: A hash table is a collection of key-value pairs. Each key is unique, and it maps to a corresponding
value.
2. Creating a Hash Table
 You can create a hash table using @{} with key-value pairs separated by =:
$hashtable = @{ "Name" = "John"; "Age" = 30; "City" = "New York" }
3. Accessing Values
 To access a value in the hash table, use the key in square brackets:
$hashtable["Name"]
This will return "John".
4. Adding or Modifying Key-Value Pairs
 You can add or update key-value pairs by specifying the key:
$hashtable["Occupation"] = "Engineer" # Adds or modifies the pair
5. Removing Key-Value Pairs
 To remove a key-value pair, use the Remove method or delete the key:
$hashtable.Remove("City") # Removes the "City" key-value pair
6. Checking if a Key Exists
 Use ContainsKey to check if a specific key exists in the hash table:
$hashtable.ContainsKey("Age") # Returns True if "Age" exists
7. Iterating Through a Hash Table
 You can loop through all the key-value pairs using a foreach loop:
foreach ($key in $hashtable.Keys) {
Write-Host "$key: $($hashtable[$key])"
}
8. Nested Hash Tables
 Hash tables can contain other hash tables as values, allowing for nested structures:
$nestedHashtable = @{
"Person" = @{ "Name" = "Alice"; "Age" = 25 }
"Location" = "Los Angeles"
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy