Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

PowerShell Fundamentals: Pipelines, Network Configuration, Data Conversion, and More, Cheat Sheet of Computer Science

A comprehensive overview of powershell fundamentals, covering topics such as pipelines, network configuration cmdlets, data conversion techniques, and error handling. It includes practical examples and explanations to help users understand and apply these concepts effectively. The document also explores advanced features like powershell remoting and background jobs, enhancing the user's ability to manage and automate tasks.

Typology: Cheat Sheet

2024/2025

Available from 12/28/2024

kunal-16
kunal-16 🇮🇳

1 document

1 / 22

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
POWERSHELL SCRIPTING
UNIT 1-------------------------------------
UNDERSTANDING PIPELINE
-SELECTING SORTING
-MEASURING OBJECTS
-FILTERING OBJECTS PIPELINE
-ENUMERATION OBJECT IN PIPELINE
-SENDING PIPELINE DATA AS OUTPUT
-PASSING THE PIPELINE DATA
-ADVANCED CONSIDERATION FOR PIPELINE DATA
NETWORK CONFIGURATION CMDLETS
POWERSHELL ADVANTAGES AND DISADVANTAGES \
CONVERT DATA TO CSV HTM JSON
UNIT 2-------------------------------------
MANIPULATING ARRAY AND HASH TABLE
-WORKING WITH ARRAY USING HASH TABLE
WMI CMI DIFFRENCE+ CODE WITH OUTPUT
CREATING REGISTERY KEY FOR FUTURE SCRIPT
UNIT 3---------------------------------------
CONDITIONAL STATEMENTS
(IF/ELSE,ELSEIF,NESTED IF/ELSE)
LOOPS
FOR
WHILE
DO WHILE
(FOR EACH LOOP)
TRY CATCH FINALLY (MOST IMPORTANT)
UNIT 4--------------------------------
COMPONENTS OF REMOTING
WHAT ARE REMOTING TECHNIQUES
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16

Partial preview of the text

Download PowerShell Fundamentals: Pipelines, Network Configuration, Data Conversion, and More and more Cheat Sheet Computer Science in PDF only on Docsity!

POWERSHELL SCRIPTING

UNIT 1-------------------------------------

UNDERSTANDING PIPELINE

- SELECTING SORTING

- MEASURING OBJECTS

- FILTERING OBJECTS PIPELINE

- ENUMERATION OBJECT IN PIPELINE

- SENDING PIPELINE DATA AS OUTPUT

- PASSING THE PIPELINE DATA

- ADVANCED CONSIDERATION FOR PIPELINE DATA

NETWORK CONFIGURATION CMDLETS

POWERSHELL ADVANTAGES AND DISADVANTAGES \

CONVERT DATA TO CSV HTM JSON

UNIT 2-------------------------------------

MANIPULATING ARRAY AND HASH TABLE

- WORKING WITH ARRAY USING HASH TABLE

WMI CMI DIFFRENCE+ CODE WITH OUTPUT

CREATING REGISTERY KEY FOR FUTURE SCRIPT

UNIT 3---------------------------------------

CONDITIONAL STATEMENTS

(IF/ELSE,ELSEIF,NESTED IF/ELSE)

LOOPS

FOR

WHILE

DO WHILE

(FOR EACH LOOP)

TRY CATCH FINALLY (MOST IMPORTANT)

UNIT 4--------------------------------

COMPONENTS OF REMOTING

WHAT ARE REMOTING TECHNIQUES

ONE TO INE ,ONE TO MANY TECHNIQUES

UNIT 5 ------------------------------------------------

HOW TO CREATE MULTIPLE USER ACCOUNTS FROM CSV

BACKGROUND JOBS

- USING BG JOB

- STARTING AND MANAGING JOBS

- USING SCHEDULED JOB (NA)

- CREATING A SCHEDULED JOB

VERIFY THE VALIDITY OF IP ADDRESS WITH ADVANTAGES

CREATING A PROFILE SCRIPT

UNIT 1-------------------------------------------------------

UNDERSTANDING PIPELINE

- SELECTING SORTING

- MEASURING OBJECTS

- FILTERING OBJECTS PIPELINE

- ENUMERATION OBJECT IN PIPELINE

- SENDING PIPELINE DATA AS OUTPUT

- PASSING THE PIPELINE DATA

- ADVANCED CONSIDERATION FOR PIPELINE DATA

Pipeline in PowerShell The pipeline (|) in PowerShell is a feature used to pass the output of one command as input to another command. It allows chaining commands together, enabling efficient data manipulation and automation.


  1. Selecting and Sorting Definition: Select-Object: Chooses specific properties from objects. Sort-Object: Orders objects based on a specified property. Example: Get-Process | Select-Object Name, CPU | Sort-Object CPU - Descending

Running W32Time Windows Time Running Spooler Print Spooler


  1. Enumeration of Objects in Pipeline Definition: ForEach-Object applies actions or transformations to each item in the pipeline. Example: Get-Service | ForEach-Object {$_.Name} Output: W32Time Spooler Winmgmt

  1. Sending Pipeline Data as Output Definition: Use Out-File or Export-Csv to save pipeline output. Example: Get-Process | Out-File - FilePath processes.txt

Output: Data is saved to processes.txt.

  1. Passing the Pipeline Data Definition: Tee-Object splits the pipeline output so it can be both processed and saved. Example: Get-Process | Tee-Object - FilePath processes.txt | Select-Object Name, CPU Output: Name CPU

chrome 124.

explorer 20.

  1. Advanced Considerations for Pipeline Data Definition: Use script blocks for advanced logic when handling pipeline data. Example: Get-Service | ForEach-Object { if ($.Status - eq "Running") { $.Name.ToUpper() } } Output: W32TIME SPOOLER WINMGMT

These examples demonstrate how to use pipelines effectively for different tasks. Let me know if you need further assistance!



NETWORK CONFIGURATION CMDLETS Network Configuration Cmdlets in PowerShell These cmdlets help manage network settings like IP addresses, DNS servers, routing tables, and firewall rules. They enable configuration, troubleshooting, and automation of network tasks on Windows systems. Managing IP Addresses---- Cmdlets to view, assign, or remove IP addresses on network adapters. New-NetIPAddress Creates a new IP address

Cmdlets to create or modify firewall rules controlling network traffic.



PowerShell scripting is the use of PowerShell commands and scripts to automate tasks, manage systems, and configure settings on Windows and other systems through a command- line interface. POWERSHELL ADVANTAGES AND DISADVANTAGES Advantages of PowerShell:

  1. Automation: Automates tasks and simplifies administration.
  2. Object-Oriented: Works with objects, not just text.
  3. Cross-Platform: Available on Linux and macOS.
  4. Remote Management: Enables remote system management.
  5. Pipeline Support: Easily chain commands together. Disadvantages of PowerShell:
  6. Learning Curve: Difficult for beginners.
  7. Limited GUI: Primarily command-line based.
  8. Performance Issues: Slower for large datasets.
  9. Compatibility Issues: May not work on older systems.
  10. Security Risks: Can be exploited for malware.


CONVERT DATA TO CSV HTM JSON In this response, I'll demonstrate how to convert data into three different formats—CSV, HTML, and JSON—using PowerShell scripting. I'll provide short and simple PowerShell code examples for each format, along with the corresponding output.

  1. Convert Data to CSV:

Explanation: Export data into a CSV file using Export-Csv. Code: $data = @([PSCustomObject]@{Name="John"; Age=30}, [PSCustomObject]@{Name="Jane"; Age=25}) $data | Export-Csv - Path "data.csv" - NoTypeInformation Output (data.csv): "Name","Age" "John", "Jane",


  1. Convert Data to HTML: Explanation: Convert data to an HTML table using ConvertTo-Html. Code: $data = @([PSCustomObject]@{Name="John"; Age=30}, [PSCustomObject]@{Name="Jane"; Age=25}) $data | ConvertTo-Html | Out-File "data.html" Output (data.html):
    NameAge
    John30
    Jane25

  1. Convert Data to JSON: Explanation: Convert data into JSON format using ConvertTo-Json. Code:

$array = $array | Where-Object { $_ - ne 3 }

Output:

1 2 4 5 6

$array[0]

Output:

1

Manipulating Hash Tables: $hashTable = @{ "Name" = "John"; "Age" = 30 } $hashTable["Country"] = "USA"

Output:

Name John

Age 30

Country USA

$hashTable.Remove("Age")

Output:

Name John

Country USA

$hashTable["Name"]

Output:

John

Using Arrays with Hash Tables: $array = @("Apple", "Banana", "Cherry") $hashTable = @{} for ($i = 0; $i - lt $array.Length; $i++) { $hashTable[$i] = $array[$i] } $hashTable[1]

Output:

Banana

____________________________________________________________________________

_________

WMI CMI DIFFRENCE+ CODE WITH OUTPUT

WMI (Windows Management Instrumentation): WMI is a Windows-based framework that allows access to system management information such as hardware, software, and network settings. CIM (Common Information Model): CIM is a standard model for representing and accessing system information across platforms, providing a more modern and efficient way to query system data.


Querying System Information Using WMI: Command: Get-WmiObject - Class Win32_OperatingSystem Output: PSComputerName :. CSName : USER-PC Caption : Microsoft Windows 10 Pro OSArchitecture : 64-bit Version : 10.0.

Set-Location - Path "HKCU:\Software\Scripts" Example Output: PS HKCU:\Software\Scripts>

  1. Create registry setting to store PSDrive: New-ItemProperty - Path "HKCU:\Software\Scripts" - Name "PSDriveName" - Value "MyPSDrive"
  • PropertyType String Example Output: Hive: HKEY_CURRENT_USER\Software\Scripts Name Property

PSDriveName MyPSDrive

  1. Verify you can retrieve PSDriveName setting: Get-ItemProperty - Path "HKCU:\Software\Scripts" - Name "PSDriveName" Example Output: PSDriveName

MyPSDrive This sequence shows how to navigate, create keys, set properties, and verify them using PowerShell with outputs for each step.



UNIT 3------------------------------------------------------------- CONDITIONAL STATEMENTS (IF/ELSE,ELSEIF,NESTED IF/ELSE) in PowerShell scripting, conditional statements control the flow of execution based on specified conditions. The primary conditional constructs are if, elseif, and else.

  1. if Statement: Evaluates a condition; if true, it executes the associated block of code. Example: $number = 10 if ($number - gt 5) {

Write-Output "Number is greater than 5" } Output: Number is greater than 5

  1. elseif Statement: Used to specify a new condition to test if the previous if or elseif conditions were false. Example: $number = 10 if ($number - gt 15) { Write-Output "Number is greater than 15" } elseif ($number - gt 5) { Write-Output "Number is greater than 5 but less than or equal to 15" } Output: Number is greater than 5 but less than or equal to 15
  2. else Statement: Provides an alternative block of code to execute if all preceding if and elseif conditions are false. Example: $number = 3 if ($number - gt 5) { Write-Output "Number is greater than 5" } else { Write-Output "Number is 5 or less" }Output: Number is 5 or less
  3. Nested if Statements: An if statement inside another if statement allows for more complex conditional logic. Example: $number = 10 if ($number - gt 5) { if ($number - lt 15) {

Output: 01234

  1. do while loop: Executes a block of code once, then continues while the condition is true. $i = 0 do { Write-Host $i $i++ } while ($i - lt 5) Output: 01234
  2. foreach loop: Iterates over each item in a collection (array, list, etc.). $arr = 1.. foreach ($item in $arr) { Write-Host $item } Output: 12345

These loops help automate repetitive tasks in PowerShell scripting.



TRY CATCH FINALLY (MOST IMPORTANT) In PowerShell, try, catch, and finally blocks are used for error handling. Here's an explanation with code and output:

  1. try block: Contains the code that might throw an error.
  2. catch block: Executes if an error occurs in the try block.
  3. finally block: Executes regardless of whether an error occurred or not. It's typically used for cleanup actions. Code Example: try {

    Code that may cause an error

$number = 10 / 0 } catch {

Handling the error

Write-Host "An error occurred: $_" } finally {

Cleanup or final actions

Write-Host "This is the finally block." } Output: An error occurred: Attempted to divide by zero. This is the finally block. Explanation: The try block attempts to divide 10 by 0, which causes an error (Attempted to divide by zero). The catch block catches this error and prints the error message. The finally block always executes, printing its message, even though an error occurred. ErrorAction Parameter - Most PowerShell cmdlets have an - ErrorAction parameter that controls what happens when an error occurs. Some common options are - Continue - The default, it shows the error message but keeps running the script. Stop - Stops running the script when an error is encountered. SilentlyContinue - Suppresses the error message and continues. Inquire - Asks what you want to do each time an error occurs. ErrorAction Parameter - Most PowerShell cmdlets have an - ErrorAction parameter that controls what happens when an error occurs. Some common options are – Continue - The default, it shows the error message but keeps running the script. Stop - Stops running the script when an error is encountered. SilentlyContinue - Suppresses the error message and continues. Inquire - Asks what you want to do each time an error occurs.

Invoke-Command - ComputerName Server1,Server2 - ScriptBlock { Get-Process }

  1. Enter-PSSession For interactive sessions with one remote machine. Example: Enter-PSSession - ComputerName RemotePC
  2. CIM Commands Access and manage WMI objects. Example: Get-CimInstance - ClassName Win32_OperatingSystem - ComputerName RemotePC

Components of PowerShell Remoting

  1. WS-Man (Web Services for Management) A protocol used for communication between machines.
  2. Firewall and Security Ensure ports (default 5985 for HTTP, 5986 for HTTPS) are open.
  3. WinRM (Windows Remote Management) Service that enables PowerShell remoting.
  4. Authentication Supports Kerberos, NTLM, or certificate-based authentication.
  5. Endpoint A specific configuration allowing PowerShell remoting.
  6. Listener Listens for incoming connections (configured using WinRM).

One-to-One vs. One-to-Many Remoting One-to-One Remoting Interactive session with one remote computer. Uses Enter-PSSession. Example use case: Troubleshooting on a specific server. One-to-Many Remoting

Execute commands on multiple computers at once. Uses Invoke-Command. Example use case: Deploying updates or configurations across servers.



UNIT 5------------------------------------------------- BACKGROUND JOBS-USING BG JOB-STARTING AND MANAGING JOBS-USING SCHEDULED JOB (NA)-CREATING A SCHEDULED JOB Background Jobs in PowerShellBackground jobs in PowerShell allow processes to run asynchronously in the background, enabling other tasks to continue running without interruption. They are useful for multitasking and improving efficiency in scripts.


Start-Job Start-Job initiates a background job, running a script or command in the background. It does not block the session, allowing the user to perform other tasks while the job is running.


Get-Job Get-Job lists all background jobs that have been started, displaying information such as the job ID, its current status (running, completed, etc.), and other details about the job.


Receive-Job Receive-Job retrieves the results of a completed background job. This cmdlet allows you to collect any output or data generated by the job once it has finished.


Stop-Job