To submit this lab: Create a Word or Google Doc
Put all your code and screen shots of the running / completed code into your Word Doc
Save as StudentName_StudentID.docx
At the end of class: Upload your Word Document to:
Learning Outcomes:
Learning some Algorithm Economy Skills.
Student Lab Learning Guide: Windows PowerShell System Automation
This Lab workbook provides step-by-step instructions on how to set up a Windows administration environment and perform Windows PowerShell system automation tasks.
This lab learning guide is intended for students who are interested in learning how to automate various tasks using PowerShell.
Lab Setup: To set up the environment for the lab, perform the following steps:
1. Install Windows PowerShell: Ensure that Windows PowerShell is installed on your computer. You can install it from the Windows Features menu or from the Microsoft Store.
2. Enable PowerShell ISE: Launch Windows PowerShell and navigate to the Settings tab. In the left pane, select "Options" and then check "Enable PowerShell Integrated Scripting Environment (ISE)".
3. Create a Lab Workspace: Create a new folder on your desktop or a preferred location for storing your lab files. This will become your lab workspace: Call this folder “c:\march13pslab”
Open a PowerShell Command Prompt: Always run your Terminal Window as “Administrator”
Introduction to PowerShell
Before diving into specific automation tasks, let's gain a better understanding of PowerShell and its features.
PowerShell is a powerful command-line shell and scripting language that enables administrators to automate tasks and manage systems more efficiently.
1. Explore the PowerShell ISE: Launch PowerShell ISE and explore the interface. The ISE provides a user-friendly interface for entering PowerShell commands and scripts.
To start the PowerShell ISE (Integrated Scripting Environment), follow these steps:
1. **Click on the Windows Start button**: Locate the Windows icon on the bottom left of your screen.
2. **Search for PowerShell ISE**: In the search bar, type "PowerShell ISE" and press Enter.
3. **Select PowerShell ISE from the search results**: Click on the PowerShell ISE app from the search results to launch the application.
Alternatively:
4. **Use the Run Dialog Box**: You can also press `Windows key + R` to open the Run dialog box, then type "powershell_ise" and press Enter. This will directly launch the PowerShell ISE.
5. **Pin to Taskbar or Create Shortcut**: Once open, you can pin PowerShell ISE to the taskbar for quick access or create a desktop shortcut for easy future access.
By following these steps, you can easily start the PowerShell ISE and begin working with scripts and commands in a more convenient and integrated environment.
2. Learn Basic Commands: Review the syntax and basic commands used in PowerShell, such as Get-Command, Get-Process, and Start-Sleep. These commands will help you navigate through and explore your system.
3. Explore the Pipeline: PowerShell's pipeline is a set of commands that allow you to manipulate and filter data. Familiarize yourself with the pipeline operators such as |, -Where-Object, and -ExpandProperty.
Lab Exercises
Now that you are equipped with the necessary knowledge and tools, let's dive into the lab exercises.
Exercise 1: Managing Windows Services
In this exercise, you will learn how to manage Windows services using PowerShell.
1. Identify Running Services: Use the Get-Service command to list all the services currently running on your system.
2. Stop and Start Services: Use theStop-Service and Start-Service commands to stop and start specific services.
3. Configure Service Startup: Use theSet-Service command to modify a service's startup type, such as automatic or manual.
4. Check Service Status: Use theGet-Service command again to check the status and ensure that the desired service is running.
Exercise 2: Managing User Accounts
# PowerShell script to create 5 new local users and 3 groups, and add users to these groups
# User creation
$users = @(
"User1",
"User2",
"User3",
"User4",
"User5"
)
foreach ($user in $users) {
$password = ConvertTo-SecureString "P@ssw0rd123" -AsPlainText -Force
New-LocalUser -Name $user -Password $password -PasswordNeverExpires
Write-Host "Created user: $user"
}
# Group creation
$groups = @(
"Marketing",
"Sales",
"Fulfillment"
)
foreach ($group in $groups) {
New-LocalGroup -Name $group
Write-Host "Created group: $group"
}
# Adding users to groups
Add-LocalGroupMember -Group "Marketing" -Member @("User1", "User2")
Add-LocalGroupMember -Group "Sales" -Member @("User3", "User4")
Add-LocalGroupMember -Group "Fulfillment" -Member "User5"
Write-Host "Users have been added to the respective groups."
# End of script
# PowerShell script to output user and group information in LaTeX format
# Function to retrieve users in a group
function Get-UsersInGroup {
param ($groupName)
try {
$members = Get-LocalGroupMember -Group $groupName
return ($members.Name -replace '.*\\', '')
} catch {
return @()
}
}
# Retrieving all local users
$users = Get-LocalUser | Select-Object -ExpandProperty Name
# Retrieving all local groups
$groups = Get-LocalGroup | Select-Object -ExpandProperty Name
# Preparing LaTeX document
$latexDoc = @(
"\documentclass{article}",
"\usepackage[utf8]{inputenc}",
"\usepackage{longtable}",
"\begin{document}",
"\section*{Local Users and Groups}",
"\subsection*{Users}",
"\begin{itemize}"
)
foreach ($user in $users) {
$latexDoc += "\item $user"
}
$latexDoc += @(
"\end{itemize}",
"\subsection*{Groups and their Members}",
"\begin{longtable}{ll}"
)
foreach ($group in $groups) {
$members = Get-UsersInGroup -groupName $group
foreach ($member in $members) {
$latexDoc += "$group & $member \\"
}
}
$latexDoc += @(
"\end{longtable}",
"\end{document}"
)
# Output to LaTeX file
$latexDoc | Out-File -FilePath "UserGroupReport.tex"
Write-Host "LaTeX document created at UserGroupReport.tex"
# PowerShell script to output users, groups, and policy documents in LaTeX format
# Function to collect data
Function Get-Data {
$data = @{}
# Getting all users
$data['Users'] = Get-LocalUser | Select-Object -ExpandProperty Name
# Getting all groups
$data['Groups'] = Get-LocalGroup | Select-Object -ExpandProperty Name
# Getting all policy documents - replace this with actual command to get policy documents
$data['Policies'] = @("PolicyDoc1", "PolicyDoc2", "PolicyDoc3")
# Getting users in each group
$data['UsersInGroups'] = @{}
foreach ($group in $data['Groups']) {
$members = Get-LocalGroupMember -Group $group | Select-Object -ExpandProperty Name
$data['UsersInGroups'][$group] = $members
}
# Mapping users to policies - replace this with actual logic to map users to policies
$data['UsersInPolicies'] = @{
"User1" = @("PolicyDoc1", "PolicyDoc2");
"User2" = @("PolicyDoc3");
# ... add for other users
}
# Mapping policies to users - replace this with actual logic to map policies to users
$data['PoliciesForUsers'] = @{
"PolicyDoc1" = @("User1");
"PolicyDoc2" = @("User1");
"PolicyDoc3" = @("User2");
# ... add for other policies
}
return $data
}
# Function to generate LaTeX code
Function Generate-LaTeX {
param ($data)
$latexCode = @"
\documentclass{article}
\usepackage{array}
\begin{document}
\section*{System Report}
\begin{tabular}{|>{\raggedright}p{3cm}|>{\raggedright}p{3cm}|>{\raggedright\arraybackslash}p{3cm}|}
\hline
Users & Groups & Policies \tabularnewline
\hline
"@
# Adding users
foreach ($user in $data['Users']) {
$latexCode += "$user \tabularnewline\n"
}
$latexCode += "\hline\n"
# Adding groups
foreach ($group in $data['Groups']) {
$latexCode += "$group \tabularnewline\n"
}
$latexCode += "\hline\n"
# Adding policies
foreach ($policy in $data['Policies']) {
$latexCode += "$policy \tabularnewline\n"
}
$latexCode += "\hline\n"
$latexCode += @"
\end{tabular}
\end{document}
"@
return $latexCode
}
# Main script
$data = Get-Data
$latexCode = Generate-LaTeX -data $data
# Output to file
$latexCode | Out-File -FilePath "SystemReport.tex"
Write-Host "LaTeX report generated at SystemReport.tex"
This script utilizes PowerShell to gather file system details using WMI (Windows Management Instrumentation) and then formats this information into a LaTeX table.
When executed, the script will output a LaTeX document containing a table with columns for Device ID, Media Type, Size, Free Space, Volume Name, and File System for each logical disk on your system.
You can run this script in a PowerShell environment to generate the LaTeX output and then compile the LaTeX code to view the formatted file system information.
# Get details about the file system
$filesystem = Get-WmiObject Win32_LogicalDisk | Select-Object DeviceID, MediaType, Size, FreeSpace, VolumeName, FileSystem
# Start generating LaTeX code
$output = @"
\documentclass{article}
\begin{document}
\section{File System Information}
\begin{tabular}{|c|c|c|c|c|c|}
\hline
\textbf{Device ID} & \textbf{Media Type} & \textbf{Size (GB)} & \textbf{Free Space (GB)} & \textbf{Volume Name} & \textbf{File System} \\
\hline
"@
foreach ($fs in $filesystem) {
$output += "$($fs.DeviceID) & $($fs.MediaType) & $($fs.Size / 1GB) & $($fs.FreeSpace / 1GB) & $($fs.VolumeName) & $($fs.FileSystem) \\ \hline`n"
}
$output += @"
\end{tabular}
\end{document}
"@
# Output the LaTeX code
$output
“write a powershell script which will generate a report output into latex coded format all the details of the host system hardware”
This PowerShell script gathers information about the host system's hardware components such as the manufacturer, model, total physical memory, processor details (name, number of cores, max clock speed), and disk information (size and free space). It then formats this data into a detailed LaTeX report. When executed, the script will output a LaTeX document containing a comprehensive table with the host system's hardware details. You can run this script in a PowerShell environment to generate the LaTeX output and compile the LaTeX code to visualize the formatted host system hardware report.
# Get details about the host system hardware
$hardware = Get-WmiObject Win32_ComputerSystem | Select-Object Manufacturer, Model, TotalPhysicalMemory
$processor = Get-WmiObject Win32_Processor | Select-Object Name, NumberOfCores, MaxClockSpeed
$memory = Get-WmiObject Win32_PhysicalMemory | Measure-Object Capacity -Sum | ForEach-Object { "{0:N2} GB" -f ($_.Sum / 1GB) }
$disks = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 } | Select-Object DeviceID, Size, FreeSpace
# Start generating LaTeX code for the hardware report
$output = @"
\documentclass{article}
\usepackage{geometry}
\usepackage{longtable}
\geometry{margin=0.5in}
\begin{document}
\section{Host System Hardware Details}
\begin{longtable}{|c|c|}
\hline
\textbf{Property} & \textbf{Value} \\
\hline
\endhead
\hline
\endfoot
Manufacturer & $($hardware.Manufacturer) \\
Model & $($hardware.Model) \\
Total Physical Memory & $memory \\
Processor Name & $($processor.Name) \\
Number of Cores & $($processor.NumberOfCores) \\
Max Clock Speed (MHz) & $($processor.MaxClockSpeed) \\
\hline
"@
# Adding details about disks
foreach ($disk in $disks) {
$output += "$($disk.DeviceID) Size (GB) & $( '{0:N2}' -f ($disk.Size / 1GB)) \\
"
$output += "$($disk.DeviceID) Free Space (GB) & $( '{0:N2}' -f ($disk.FreeSpace / 1GB)) \\
\hline"
}
$output += @"
\end{longtable}
\end{document}
"@
# Output the LaTeX code
$output
“write a powershell script which will generate a report output into a disk file in latex coded format all the details of the host networking including network interface adapters and TCPIP stack”
This PowerShell script utilizes WMI (Windows Management Instrumentation) to gather information about network interface adapters and TCP/IP configuration of the host system. It then formats this data into a LaTeX document with a detailed table listing the properties and values for each network adapter and TCP/IP configuration. The script saves this output into a file named "Host_Networking_Report.tex". You can run this script in a PowerShell environment to generate the LaTeX report and access the saved .tex file to view the formatted host networking details.
# Get details about the host networking including network interface adapters and TCP/IP configuration
$networkAdapters = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $_.IPEnabled -eq $true } | Select-Object Description, IPAddress, MACAddress, DefaultIPGateway
$tcpipConfiguration = Get-WmiObject Win32_NetworkAdapterConfiguration | Select-Object DNSHostName, DNSServerSearchOrder
# Prepare the LaTeX output
$output = @"
\documentclass{article}
\usepackage{geometry}
\usepackage{longtable}
\geometry{margin=0.5in}
\begin{document}
\section{Host Networking Details}
\begin{longtable}{|c|c|}
\hline
\textbf{Property} & \textbf{Value} \\
\hline
"@
# Adding details about network adapters
foreach ($adapter in $networkAdapters) {
$output += "Description & $($adapter.Description) \\
"
$output += "IP Address & $($adapter.IPAddress -join ', ') \\
"
$output += "MAC Address & $($adapter.MACAddress) \\
"
$output += "Default Gateway & $($adapter.DefaultIPGateway -join ', ') \\
\hline
"
}
# Adding details about TCP/IP configuration
foreach ($config in $tcpipConfiguration) {
$output += "DNS Host Name & $($config.DNSHostName) \\
"
$output += "DNS Servers & $($config.DNSServerSearchOrder -join ', ') \\
\hline
"
}
# Finish the LaTeX document
$output += @"
\end{longtable}
\end{document}
"@
# Output the LaTeX code to a .tex file
$output | Out-File -FilePath "Host_Networking_Report.tex"
“write a powershell script which will output to the powershell terminal in real time the tcp packets transiting over the network adapter”
Monitoring real-time TCP packets transiting over a network adapter in PowerShell can be achieved using the NetEventSession module. Here's a script to accomplish this:
In this script:
Start-NetEventSession initiates a real-time capture of TCP traffic. You can adjust the parameters like the file path and capture level as needed. Get-NetEventSession retrieves the session details. Receive-NetEventSession displays the real-time TCP packets as they transit over the network adapter. Execute this script in a PowerShell environment to start capturing and displaying real-time TCP packets transiting over the network adapter on the terminal. Adjust the capture settings to suit your monitoring needs or filtering conditions.
# Start a real-time capture of TCP traffic
Start-NetEventSession -Name "TCP_Packets" -LocalFilePath "C:\Temp\TCP_Packets.etl" -CaptureMode RealTime -Level Information -ProviderName Microsoft-Windows-TCPIP
# Start capturing TCP packets
netsh trace start capture = yes report = yes persistent = yes maxSize = 1024 filemode = circular overwrite = yes tracefile = "C:\Temp\TCP_P.etl"
# Display real-time captured TCP packets
netsh trace show capture
In this exercise, you will learn how to manage user accounts using PowerShell.
1. Identify User Accounts: Use theGet-LocalUser command to list all the user accounts on your system.
2. Create and Delete User Accounts: Use theNew-LocalUser and Remove-LocalUser commands to create and delete user accounts.
3. Modify User Properties: Use theSet-LocalUser command to modify a user's properties, such as password and home directory.
4. Check User Status: Use theGet-LocalUser command again to check the status and ensure that the desired user account exists.
Exercise 3: Managing Registry Keys
In this exercise, you will learn how to manage registry keys using PowerShell.
1. Identify Registry Keys: Use theGet-ItemProperty command to list all the registry keys in a specific location.
2. Modify Registry Values: Use theSet-ItemProperty command to modify the value of a registry key.
3. Delete Registry Keys: Use theRemove-ItemProperty command to delete a registry key.
4. Check Registry Value: Use theGet-ItemProperty command again to check the value and ensure that the desired registry key is present.
Exercise 4: Managing Event Logs
In this exercise, you will learn how to manage event logs using PowerShell.
1. Identify Event Logs: Use theGet-EventLog command to list all the event logs on your system.
2. Filter Event Logs: Use theWhere-Object filter to find specific events or events related to a specific keyword.
3. Export Event Logs: Use theExport-EventLog command to export event logs to a CSV file or a text file.
4. Clear Event Logs: Use theClear-EventLog command to clear all event logs.
Conclusion: By completing these exercises, you should have a solid foundation in Windows PowerShell system automation. Remember to practice and explore further to refine your automation skills. Good luck and happy scripting! 💪💻