Share
Explore

PowerShell Exercises for Windows Administation Automation

image.png
Also study this LINKED Resource:
megaphone

Lecture: Understanding Windows PowerShell and WMI (Windows Management Instrumentation)
#### Introduction
Welcome to today's lecture on Windows PowerShell and Windows Management Instrumentation (WMI).
PowerShell is a powerful scripting language and command-line shell that is used for system administration and automation.
WMI, on the other hand, is a set of specifications from Microsoft for consolidating the management of devices and applications in a network.
#### Understanding WMI
1. **What is WMI?** - Windows Management Instrumentation (WMI) is a core component of the Windows operating system. - It enables the management of data and operations on Windows-based systems.
- Essentially, WMI provides a standardized method to access information about a computer system, both hardware, and software.

2. **WMI Architecture**
- WMI is built on the Web-Based Enterprise Management (WBEM) and Common Information Model (CIM) standards.
- It allows for data to be gathered about a machine, such as CPU usage, installed applications, hardware configuration, etc.

PowerShell and WMI

1. **PowerShell and WMI Integration**

- PowerShell uses WMI to perform a wide range of system administration tasks.
- This integration provides administrators with powerful tools to query, update, and manage Windows systems.

2. **Basic WMI Cmdlets in PowerShell**
- `Get-WmiObject`: This cmdlet is the cornerstone for interacting with WMI Windows Management Instrumentation. It can be used to retrieve WMI objects.
- Example:
`Get-WmiObject -Class Win32_BIOS` retrieves information about the BIOS of the system.

3. **Exploring WMI Classes** - WMI classes represent various types of objects in a system.
For instance, `Win32_Process` represents processes,
`Win32_Service` for services, etc.
You will now explore WMI classes using PowerShell to generate reports on specific pieces of information. This is a typical on the job work activity.
Resource: Lab Workbook on WMI Query Language:
//
The Get-WmiObject cmdlet in PowerShell is versatile and supports several parameters in addition to -Class.
Here's a list of key parameters that you can use with Get-WmiObject:
-Class <string>
Specifies the name of the WMI class. For example, Win32_BIOS.
-Namespace <string>
Specifies the WMI repository namespace. The default is root\cimv2.
-ComputerName <string[]>
Specifies the remote computer(s) on which the WMI command is run. The default is the local computer.
-Credential <PSCredential>
Specifies a user account that has permission to perform the action. The default is the current user.
-Filter <string>
Specifies a WHERE clause to apply to the WMI query.
-Query <string>
Specifies a WMI Query Language (WQL) statement to run.
This allows for more complex queries than what -Filter provides.
-Impersonation <ImpersonationLevel>
Specifies the impersonation level to use when connecting to WMI.
Possible levels are Default, None, Identify, Impersonate, and Delegate.
-Authentication <AuthenticationLevel>
Specifies the authentication level to use.
It ranges from Unchanged to PacketPrivacy.
-Locale <string>
Specifies the locale to use for the WMI query.
-Authority <string>
Specifies the authority level to use when authenticating the user.
-Amended
Adds localized information for the class, if available.
-DirectRead
Retrieves information directly from a WMI class rather than an instance of the class.
-EnableAllPrivileges
Enables all the privileges of the current user while the command is being run.
-ThrottleLimit <int>
Specifies the maximum number of concurrent connections that can be established to run the command.
-AsJob
Runs the command as a background job.
-List
Lists WMI classes or WMI class methods, properties, and qualifiers.
These parameters can greatly extend the functionality of the Get-WmiObject cmdlet, allowing for specific, targeted queries and operations on the WMI data of local and remote systems. Remember to use these parameters carefully, especially when working with remote systems and when running commands that require elevated privileges.
//

#### Practical Examples
1. **Example 1: Retrieving System Information** - You can retrieve detailed system information such as CPU, memory, and disk details using WMI. - For instance, `Get-WmiObject -Class Win32_PhysicalMemory` provides details about the physical memory of the system.
2. **Example 2: Managing Processes and Services** - PowerShell and WMI can be used to manage Windows processes and services. - For example, you can start, stop, or restart services on a local or remote machine.
3. **Remote Management with WMI** - WMI allows for remote management of computers, a crucial feature for system administrators. - You can execute WMI queries against remote machines to retrieve or configure information.
#### Advanced Topics
1. **WMI Eventing** - WMI can be used to listen for system events, like creation or termination of a process, changes in system configuration, etc. - This aspect is particularly useful for real-time monitoring and automation.
2. **Security and Permissions** - Managing security and permissions is crucial while dealing with WMI. - PowerShell sessions need to have the appropriate permissions to interact with WMI, especially for remote management.
#### Conclusion
Understanding and leveraging the power of PowerShell in combination with WMI provides system administrators and developers with an incredibly powerful toolkit. Whether it’s for automating routine tasks, querying system information, or managing remote systems, these tools are indispensable in the realm of Windows system administration.
#### Further Learning - Practice writing PowerShell scripts that utilize WMI. - Explore WMI classes and instances to get a deeper understanding of the system. - Remember, practical application and experimentation are key to mastering PowerShell and WMI.
#### Questions?
This concludes our lecture. I hope this session has provided you with a solid understanding of PowerShell and WMI. Now, I would be happy to take any questions you might have.

Starting Windows PowerShell ISE (Integrated Scripting Environment) is quite straightforward.

Here are a few methods you can use:

Method 1: Using the Start Menu

1. Click on the Start Menu. 2. Type `PowerShell ISE`. 3. Click on `Windows PowerShell ISE` from the search results. This should open the application.
### Method 2: Using the Run Dialog 1. Press `Windows Key + R` to open the Run dialog box. 2. Type `powershell_ise.exe` and press Enter. This command should launch the PowerShell ISE.
### Method 3: From the PowerShell Command Line 1. Open Windows PowerShell (not ISE). 2. Type `start powershell_ise` and press Enter. This will open the PowerShell ISE.
### Method 4: Using the Taskbar (If Pinned) 1. If you have PowerShell ISE pinned to your taskbar, simply click on its icon to start it.
### Additional Tips - On Windows 10 and later, PowerShell ISE is included by default but it is considered a "legacy" feature, and Microsoft encourages the use of Visual Studio Code with the PowerShell extension as an alternative for more advanced scripting. - Make sure you have the necessary permissions to open PowerShell ISE if you are on a restricted or managed device.
Using PowerShell ISE, you can write, run, and debug scripts in a more user-friendly environment compared to the traditional PowerShell console.

### PowerShell Code Labs for Windows System Administration Exercises

1. **Gathering System Information**
- Use PowerShell's `Get-WmiObject` cmdlet to retrieve system details such as CPU, memory, and disk information.
- Display the system information in a formatted output using PowerShell.
2. **Managing Files and Directories** - Utilize PowerShell cmdlets such as `New-Item`, `Copy-Item`, and `Remove-Item` for file and directory operations. - Search for files based on patterns using the `Get-ChildItem` cmdlet.
3. **Automating User Management** - Leverage PowerShell to create, modify, and delete user accounts using cmdlets such as `New-LocalUser`, `Set-LocalUser`, and `Remove-LocalUser`. - Manage user groups and permissions using PowerShell cmdlets. - Generate reports on user activities and login history using PowerShell commands.
4. **Scheduling Tasks and Scripts** - Use PowerShell's `Register-ScheduledTask` cmdlet to schedule tasks and scripts for automation. - Create scripts to automate recurring administration tasks and configure them to run at specific times or intervals.
5. **Monitoring System Performance** - Utilize PowerShell to monitor CPU usage, memory consumption, and disk space using cmdlets such as `Get-Counter`. - Collect performance metrics and generate reports using PowerShell. - Set up alerts and notifications for critical thresholds using PowerShell cmdlets.
These PowerShell Code Labs align with the Python exercises and cover essential Windows system administration tasks, offering practical experience in using PowerShell for automation and management.
For more detailed information on PowerShell cmdlets and their usage, refer to [PowerShell Documentation](https://docs.microsoft.com/en-us/powershell/).
Detailed PowerShell scripts for each of these lab exercises:

1. Gathering System Information
To gather system information such as CPU, memory, and disk information, and then display it in a formatted manner, you can use the Get-WmiObject cmdlet.

powershell
Copy code
# CPU Information
$cpu = Get-WmiObject Win32_Processor
Write-Host "CPU Model: $($cpu.Name)"

# Memory Information
$memory = Get-WmiObject Win32_PhysicalMemory
foreach ($mem in $memory) {
Write-Host "Memory Capacity: $($mem.Capacity / 1GB) GB"
}

# Disk Information
$disks = Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3"
foreach ($disk in $disks) {
Write-Host "Disk $($disk.DeviceID) - $($disk.Size / 1GB) GB"
}
2. Managing Files and Directories
For file and directory operations, you can use various cmdlets like New-Item, Copy-Item, and Remove-Item. Here's an example script:

powershell
Copy code
# Creating a new directory
New-Item -Path 'C:\MyDirectory' -ItemType Directory

# Copying a file
Copy-Item -Path 'C:\MyDirectory\file.txt' -Destination 'C:\MyDirectory\file_copy.txt'

# Removing a file
Remove-Item -Path 'C:\MyDirectory\file_copy.txt'

# Searching for files with a specific pattern
Get-ChildItem -Path 'C:\MyDirectory' -Filter '*.txt'
3. Automating User Management
PowerShell allows you to manage local user accounts effectively:

powershell
Copy code
# Creating a new user
$Password = ConvertTo-SecureString 'Pa$$w0rd' -AsPlainText -Force
New-LocalUser "NewUser" -Password $Password

# Modifying a user
Set-LocalUser -Name "NewUser" -PasswordNeverExpires

# Removing a user
Remove-LocalUser -Name "NewUser"

# Managing user groups
Add-LocalGroupMember -Group "Administrators" -Member "NewUser"

# Reporting on user activities
# Note: This requires additional setup for auditing and logging
4. Scheduling Tasks and Scripts
To schedule a task that runs a script:

powershell
Copy code
$Action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-File "C:\Scripts\MyScript.ps1"'
$Trigger = New-ScheduledTaskTrigger -At 9am -Daily
Register-ScheduledTask -Action $Action -Trigger $Trigger -TaskName "MyDailyTask"
5. Monitoring System Performance
Monitoring performance can involve various cmdlets. Here’s a simple example for CPU and memory:

powershell
Copy code
# CPU Usage
$cpuUsage = Get-Counter '\Processor(_Total)\% Processor Time'
Write-Host "CPU Usage: $($cpuUsage.CounterSamples.CookedValue)%"

# Memory Usage
$memoryUsage = Get-Counter '\Memory\Available MBytes'
Write-Host "Available Memory: $($memoryUsage.CounterSamples.CookedValue) MB"
These scripts provide a foundation for the tasks described in the labs. For more complex scenarios, especially for user management and performance monitoring, additional configuration and cmdlets may be required. Also, always ensure you have the necessary permissions to execute these scripts, particularly when modifying system settings or user accounts.

megaphone

A fun way to conclude a PowerShell class is to create a simple game.

Let’s create a PowerShell script for a classic "Guess the Number" game.

This will not only be entertaining but also reinforce some basic PowerShell concepts.

### PowerShell "Guess the Number" Game

#### Game Overview The game randomly selects a number within a given range, and the player has to guess the number. After each guess, the game will tell the player if the guess is too high, too low, or correct.
#### Script
```powershell # PowerShell Guess the Number Game
function Start-Game { # Generate a random number between 1 and 100 $secretNumber = Get-Random -Minimum 1 -Maximum 101 $userGuess = 0 $tries = 0
Write-Host "Guess the number I am thinking of (between 1 and 100)."
# Loop until the correct guess while ($userGuess -ne $secretNumber) { $userGuess = Read-Host "Enter your guess" $tries++
# Input validation if ($userGuess -match "^\d+$") { $userGuess = [int]$userGuess
# Check if the guess is correct, high, or low if ($userGuess -eq $secretNumber) { Write-Host "Congratulations! You guessed the correct number in $tries tries!" } elseif ($userGuess -gt $secretNumber) { Write-Host "Too high! Try a smaller number." } else { Write-Host "Too low! Try a higher number." } } else { Write-Host "Please enter a valid number." } } }
# Start the game Start-Game ```
#### How to Play 1. Copy the script and paste it into the PowerShell ISE or any PowerShell console. 2. Run the script. 3. Follow the on-screen instructions to guess a number. 4. The game provides feedback on each guess and continues until the correct number is guessed.
#### Learning Objectives Covered - **Basic Function Creation**: `function Start-Game {...}` - **Random Number Generation**: `$secretNumber = Get-Random -Minimum 1 -Maximum 101` - **Conditional Logic**: `if`, `elseif`, `else` statements - **Loops**: `while` loop for repeated guessing - **User Input**: `$userGuess = Read-Host "Enter your guess"` - **Input Validation**: Checking if the input is a number
#### Conclusion This simple PowerShell game demonstrates how to combine various PowerShell concepts into something interactive and enjoyable. It's a great way to wrap up a class, showing students the versatility of PowerShell in a fun and engaging way.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.