Windows PowerShell
目录
Task1 Introduction 引言
Task2 What Is PowerShell 什么是 PowerShell
图片版
文字版
From the official Microsoft page: “PowerShell is a cross-platform task automation solution made up of a command-line shell, a scripting language, and a configuration management framework.”
微软官方网站称:“PowerShell 是一个跨平台的任务自动化解决方案,由命令行 shell、脚本语言和组态管理框架组成。”
PowerShell is a powerful tool from Microsoft designed for task automation and configuration management. It combines a command-line interface and a scripting language built on the .NET framework. Unlike older text-based command-line tools, PowerShell is object-oriented, which means it can handle complex data types and interact with system components more effectively. Initially exclusive to Windows, PowerShell has lately expanded to support macOS and Linux, making it a versatile option for IT professionals across different operating systems.
PowerShell 是一个来自微软的强大工具,专为任务自动化和组态管理而设计。它结合了命令行界面和基于.NET 框架构建的脚本语言。与较旧的基于文本的命令行界面工具不同,PowerShell 是面向对象的,这意味着它可以更有效地处理复杂的数据类型并与系统组件交互。PowerShell 最初仅限于 Windows, 最近已扩展到支持 macOS 和 Linux, 使其成为不同操作系统的 IT 专业人员的多功能选择。
A Brief History of PowerShellPowerShell 简史
PowerShell was developed to overcome the limitations of existing command-line tools and scripting environments in Windows. In the early 2000s, as Windows was increasingly used in complex enterprise environments, traditional tools like cmd.exe
and batch files fell short in automating and managing these systems. Microsoft needed a tool that could handle more sophisticated administrative tasks and interact with Windows’ modern APIs.
PowerShell 的开发旨在克服 Windows 中现有命令行工具和脚本环境的局限性。在 21 世纪初,随着 Windows 在复杂的企业环境中的使用越来越多,像 cmd.exe 和批处理文件这样的传统工具在自动化和管理这些系统方面已经不足。微软需要一个能够处理更复杂管理任务并与 Windows 的现代 API 交互的工具。
Jeffrey Snover, a Microsoft engineer, realised that Windows and Unix handled system operations differently—Windows used structured data and APIs, while Unix treated everything as text files. This difference made porting Unix tools to Windows impractical. Snover’s solution was to develop an object-oriented approach, combining scripting simplicity with the power of the .NET framework. Released in 2006, PowerShell allowed administrators to automate tasks more effectively by manipulating objects, offering deeper integration with Windows systems.
微软工程师 Jeffrey Snover 意识到 Windows 和 Unix 处理系统操作的方式不同 ——Windows 使用结构化数据和 API, 而 Unix 将一切都视为文本文件。这种差异使得将 Unix 工具移植到 Windows 变得不切实际。Snover 的解决方案是开发一种面向对象的方法,将脚本的简单性与.NET 框架的强大功能相结合。2006 年发布的 PowerShell 允许管理员通过操作对象来更有效地自动化任务,提供了与 Windows 系统的更深层次集成。
As IT environments evolved to include various operating systems, the need for a versatile automation tool grew. In 2016, Microsoft responded by releasing PowerShell Core, an open-source and cross-platform version that runs on Windows, macOS, and Linux.
随着 IT 环境演变为包含各种操作系统,对通用自动化工具的需求也随之增长。2016 年,微软发布了 PowerShell Core 作为回应,这是一个开源的跨平台版本,可以在 Windows、macOS 和 Linux 上运行。
The Power in PowerShellPowerShell 的强大功能
To fully grasp the power of PowerShell, we first need to understand what an object is in this context.
为了充分理解 PowerShell 的强大功能,我们首先需要理解在这种情况下对象是什么。
In programming, an object represents an item with properties (characteristics) and methods (actions). For example, a car
object might have properties like Color
, Model
, and FuelLevel
, and methods like Drive()
, HonkHorn()
, and Refuel()
.
在编程中,对象表示具有属性 (特征) 和方法 (动作) 的项目。例如,汽车对象可能具有 Color、Model 和 FuelLevel 等属性,以及 Drive ()、HonkHorn () 和 Refuel () 等方法。
Similarly, in PowerShell, objects are fundamental units that encapsulate data and functionality, making it easier to manage and manipulate information. An object in PowerShell can contain file names, usernames or sizes as data (properties), and carry functions (methods) such as copying a file or stopping a process.
同样,在 PowerShell 中,对象是封装数据和功能的基本单元,使管理和操作信息变得更加容易。PowerShell 中的对象可以包含文件名、用户名或大小作为数据 (属性), 并携带函数 (方法), 如复制文件或停止进程。
The traditional Command Shell’s basic commands are text-based, meaning they process and output data as plain text. Instead, when a cmdlet (pronounced command-let) is run in PowerShell, it returns objects that retain their properties and methods. This allows for more powerful and flexible data manipulation since these objects do not require additional parsing of text.
传统 Command Shell 的基本命令是基于文本的,这意味着它们以纯文本的形式处理和输出数据。相反,当在 PowerShell 中运行 cmdlet (发音为 command-let) 时,它会返回保留其属性和方法的对象。这允许更强大和灵活的数据操作,因为这些对象不需要额外的文本解析。
We will explore more about PowerShell’s cmdlets and their capabilities in the upcoming sections.
我们将在后续章节中详细探讨 PowerShell 的 Cmdlet 及其功能。
问题
答案
Task3 PowerShell Basics PowerShell 基础
图片版
文字版
Before continuing on our PowerShell journey, let’s connect to our lab environment. Press the Start Machine
button, then start the AttackBox by pressing the Start AttackBox
button at the top of this page. The AttackBox machine will start in Split-Screen view. If it is not visible, use the blue Show Split View
button at the top of the page.
在继续我们的 PowerShell 之旅之前,让我们连接到我们的实验室环境。按下 Start Machine 按钮,然后通过按下本页顶部的 Start AttackBox 按钮来启动 AttackBox。AttackBox 机器将在分屏视图中启动。如果它不可见,请使用页面顶部的蓝色 Show Split View 按钮。
Start Machine启动机器
You can follow the steps below to connect to the target VM via SSH using the Remmina client.
您可以按照以下步骤使用 Remina 客户端通过 SSH 连接到目标 VM。
- Click on 点击Applications应用程序, marked with number 1 in the screenshot below. Select
, 在下面的截图中用数字 1 标记。选择Internet互联网 (number 2), then (数字 2), 然后Remmina回忆 (number 3).(数字 3)。 - A popup window will appear, prompting you for a password to unlock the AttackBox's keyring. Click on
一个弹出窗口将出现,提示您输入密码以解锁 AttackBox 的钥匙环。点击Cancel
to ignore the prompt.忽略提示。 - Select the 选择SSH option from the dropdown (number 1 in the screenshot below), then paste the target IP:
从下拉选项 (下面截图中的第 1 个选项) 中选择,然后粘贴目标 IP:MACHINE_IP
in the bar at the top (number 2). Finally, click
在顶部的栏中 (编号 2)。最后,单击Enter
. - In the next window, enter the credentials found in the card below, then click on
OK
.
在下一个窗口中,输入下面卡片中找到的凭据,然后点击确定。
Username 用户名 | captain船长 |
Password 密码 |
|
IP | MACHINE_IP |
Launching PowerShell启动 PowerShell
PowerShell can be launched in several ways, depending on your needs and environment. If you are working on a Windows system from the graphical interface (GUI), these are some of the possible ways to launch it:
PowerShell 可以通过多种方式启动,具体取决于您的需求和环境。如果您正在使用图形界面 (GUI) 的 Windows 系统,以下是一些可能的启动方式:
- Start Menu: Type
powershell
in the Windows Start Menu search bar, then click onWindows PowerShell
orPowerShell
from the results.
开始菜单:在 Windows 开始菜单搜索栏中键入 PowerShell, 然后从结果中单击 Windows PowerShell 或 PowerShell。 - Run Dialog: Press
Win + R
to open theRun
dialog, typepowershell
, and hitEnter
.
运行对话框:按 Win + R 打开 “运行” 对话框,键入 PowerShell, 然后按 Enter 键。 - File Explorer: Navigate to any folder, then type
powershell
in the address bar, and pressEnter
. This opens PowerShell in that specific directory.
文件资源管理器:导航到任何文件夹,然后在地址栏中键入 PowerShell, 并按 Enter 键。这将在该特定目录中打开 PowerShell。 - Task Manager: Open the Task Manager, go to
File > Run new task
, typepowershell
, and pressEnter
.
任务管理器:打开任务管理器,导航到文件 > 运行新任务,键入 powershell, 然后按回车键。
Alternatively, PowerShell can be launched from a Command Prompt (cmd.exe
) by typing powershell
, and pressing Enter
.
或者,可以通过键入 powershell 并按回车键,从命令提示符 (cmd.exe) 启动 PowerShell。
In our case, where we only have access to the target VM’s Command Prompt, this is the method we’ll use.
在我们的例子中,我们只能访问目标虚拟机的命令提示符,因此我们将使用这种方法。
Terminal终端
captain@THEBLACKPEARL C:\Users\captain>powershell
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindowsPS C:\Users\captain>
After PowerShell has launched, we’re presented with a PS
(which stands for PowerShell
) prompt in the current working directory.
在 PowerShell 启动后,我们会在当前工作目录中看到一个 PS (代表 PowerShell) 提示符。
Basic Syntax: Verb-Noun基本语法:动词 - 名词
As previously mentioned, PowerShell commands are known as cmdlets
(pronounced command-lets
). They are much more powerful than the traditional Windows commands and allow for more advanced data manipulation.
如前所述,PowerShell 命令被称为 cmdlet (发音为 command-let)。它们比传统的 Windows 命令强大得多,并允许进行更高级的数据操作。
Cmdlets follow a consistent Verb-Noun
naming convention. This structure makes it easy to understand what each cmdlet does. The Verb
describes the action, and the Noun
specifies the object on which action is performed. For example:
Cmdlet 遵循一致的动词 - 名词变数命名原则。这种结构使得理解每个 Cmdlet 的功能变得容易。动词描述动作,名词指定执行动作的对象。例如:
Get-Content
: Retrieves (gets) the content of a file and displays it in the console.
Get-Content: 检索 (获取) 文件的内容并将其显示在控制台中。Set-Location
: Changes (sets) the current working directory.
设置位置:更改 (设置) 当前工作目录。
Basic Cmdlets
To list all available cmdlets, functions, aliases, and scripts that can be executed in the current PowerShell session, we can use Get-Command
. It’s an essential tool for discovering what commands one can use.
要列出所有可以在当前 PowerShell 会话中执行的可用 cmdlet、函数、别名和脚本,我们可以使用 Get-Command。这是一个必不可少的工具,用于发现可以使用哪些命令。
Terminal终端
PS C:\Users\captain> Get-CommandCommandType Name Version Source
----------- ---- ------- ------ Alias Add-AppPackage 2.0.1.0 Appx
Alias Add-AppPackageVolume 2.0.1.0 Appx
Alias Add-AppProvisionedPackage 3.0 Dism
[...]
Function A:
Function Add-BCDataCacheExtension 1.0.0.0 BranchCache
Function Add-DnsClientDohServerAddress 1.0.0.0 DnsClient
[...]
Cmdlet Add-AppxPackage 2.0.1.0 Appx
Cmdlet Add-AppxProvisionedPackage 3.0 Dism
Cmdlet Add-AppxVolume 2.0.1.0 Appx
[...]
For each CommandInfo
object retrieved by the cmdlet, some essential information (properties) is displayed on the console. It’s possible to filter the list of commands based on displayed property values. For example, if we want to display only the available commands of type “function”, we can use -CommandType "Function"
, as shown below:
对于 cmdlet 检索到的每个 CommandInfo 对象,控制台上都会显示一些基本信息 (属性)。可以根据显示的属性值筛选命令列表。例如,如果我们只想显示 “function” 类型的可用命令,可以使用 -CommandType “Function”, 如下所示:
Terminal终端
PS C:\Users\captain> Get-Command -CommandType "Function"CommandType Name Version Source
----------- ---- ------- ------
Function A:
Function Add-BCDataCacheExtension 1.0.0.0 BranchCache
Function Add-DnsClientDohServerAddress 1.0.0.0 DnsClient
Function Add-DnsClientNrptRule 1.0.0.0 DnsClient
[...]
We will learn more efficient ways to filter output from cmdlets in the upcoming tasks.
在接下来的任务中,我们将学习更高效的方法来过滤来自 cmdlet 的输出。
Another essential cmdlet to keep in our tool belt is Get-Help
: it provides detailed information about cmdlets, including usage, parameters, and examples. It’s the go-to cmdlet for learning how to use PowerShell commands.
另一个需要保存在工具腰带中的重要 Cmdlet 是 Get-Help: 它提供了关于 Cmdlet 的详细信息,包括使用、参数和示例。它是学习如何使用 PowerShell 命令的入门 Cmdlet。
Terminal终端
PS C:\Users\captain> Get-Help Get-DateNAMEGet-DateSYNOPSISGets the current date and time.SYNTAXGet-Date [[-Date] <System.DateTime>] [-Day <System.Int32>] [-DisplayHint {Date | Time | DateTime}] [-Format <System.String>] [-Hour <System.Int32>] [-Millisecond <System.Int32>] [-Minute <System.Int32>] [-Month <System.Int32>] [-Second <System.Int32>] [-Year <System.Int32>] [<CommonParameters>]Get-Date [[-Date] <System.DateTime>] [-Day <System.Int32>] [-DisplayHint {Date | Time | DateTime}] [-Hour <System.Int32>] [-Millisecond <System.Int32>] [-Minute <System.Int32>] [-Month <System.Int32>] [-Second <System.Int32>] [-UFormat <System.String>] [-Year <System.Int32>] [<CommonParameters>]DESCRIPTIONThe `Get-Date` cmdlet gets a DateTime object that represents the current date or a date that you specify. `Get-Date` can format the date and time in several .NET and UNIX formats. You can use `Get-Date` to generate a date or time character string, and then send the string to other cmdlets or programs.`Get-Date` uses the current culture settings of the operating system to determine how the output is formatted. To view your computer's settings, use `(Get-Culture).DateTimeFormat`.RELATED LINKSOnline Version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-date?view=powershell-5.1&WT.mc_id=ps-gethelpForEach-ObjectGet-CultureGet-MemberNew-ItemNew-TimeSpanSet-DateSet-Culture xref:International.Set-CultureREMARKSTo see the examples, type: "get-help Get-Date -examples".For more information, type: "get-help Get-Date -detailed".For technical information, type: "get-help Get-Date -full".For online help, type: "get-help Get-Date -online".
As shown in the results above, Get-Help
informs us that we can retrieve other useful information about a cmdlet by appending some options to the basic syntax. For example, by appending -examples
to the command displayed above, we will be shown a list of common ways in which the chosen cmdlet can be used.
如上面的结果所示,Get-Help 通知我们可以通过在基本语法中添加一些选项来检索关于 Cmdlet 的其他有用信息。例如,通过在上面显示的命令中添加 - examples, 我们将看到一个常见方式列表,其中包含了所选 Cmdlet 的使用方式。
To make the transition easier for IT professionals, PowerShell includes aliases —which are shortcuts or alternative names for cmdlets— for many traditional Windows commands. Indispensable for users already familiar with other command-line tools, Get-Alias
lists all aliases available. For example, dir
is an alias for Get-ChildItem
, and cd
is an alias for Set-Location
.
为了让 IT 专业人员更容易过渡,PowerShell 包括别名 —— 这是许多传统 Windows 命令的快捷方式或替代名称。对于已经熟悉其他命令行工具的用户来说,Get-Alias 列出了所有可用的别名。例如,dir 是 Get-ChildItem 的别名,cd 是 Set-Location 的别名。
Terminal终端
PS C:\Users\captain> Get-AliasCommandType Name Version Source
----------- ---- ------- ------
Alias % -> ForEach-Object
Alias ? -> Where-Object
Alias ac -> Add-Content
Alias asnp -> Add-PSSnapin
Alias cat -> Get-Content
Alias cd -> Set-Location
Alias CFS -> ConvertFrom-String 3.1.0.0 Microsoft.PowerShell.Utility
Alias chdir -> Set-Location
Alias clc -> Clear-Content
Alias clear -> Clear-Host
[...]
Where to Find and Download Cmdlets
在哪里查找和下载 Cmdlets
Another powerful feature of PowerShell is the possibility of extending its functionality by downloading additional cmdlets from online repositories.
PowerShell 的另一个强大功能是可以通过从在线仓库下载额外的 Cmdlet 来扩展其功能。
NOTE: Please note that the cmdlets listed in this section require a working internet connection to query online repositories. The attached machine doesn't have access to the internet, therefore these commands won't work in this environment.
注意:请注意,本节中列出的 Cmdlet 需要正常的互联网连接才能查询在线存储库。附加的机器无法访问互联网,因此这些命令在这种环境中将不起作用。
To search for modules (collections of cmdlets) in online repositories like the PowerShell Gallery, we can use Find-Module
. Sometimes, if we don’t know the exact name of the module, it can be useful to search for modules with a similar name. We can achieve this by filtering the Name
property and appending a wildcard (*
) to the module’s partial name, using the following standard PowerShell syntax: Cmdlet -Property "pattern*"
.
要在 PowerShell 库等在线存储库中搜索模块 (cmdlet 的集合), 可以使用 Find-Module。有时,如果我们不知道模块的确切名称,搜索名称相似的模块可能会很有用。我们可以通过过滤 Name 属性并在模块的部分名称后添加通配符 (*) 来实现这一点,使用以下标准 PowerShell 语法:cmdlet -Property“pattern*”。
Terminal终端
PS C:\Users\captain> Find-Module -Name "PowerShell*" Version Name Repository Description
------- ---- ---------- -----------
0.4.7 powershell-yaml PSGallery Powershell module for serializing and deserializing YAML2.2.5 PowerShellGet PSGallery PowerShell module with commands for discovering, installing, updating and publishing the PowerShell artifacts like Modules, DSC Resources, Role Capabilities and Scripts.
1.0.80.0 PowerShell.Module.InvokeWinGet PSGallery Module to Invoke WinGet and parse the output in PSOjects0.17.0 PowerShellForGitHub PSGallery PowerShell wrapper for GitHub API
Once identified, the modules can be downloaded and installed from the repository with Install-Module
, making new cmdlets contained in the module available for use.
一旦确定,就可以使用 Install-Module 从存储库下载和安装模块,使模块中包含的新 cmdlet 可供使用。
Terminal终端
PS C:\Users\captain> Install-Module -Name "PowerShellGet"Untrusted repository
You are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from 'PSGallery'?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"):
With these essential tools in our belt, we can now start exploring PowerShell’s capabilities.
有了这些必要的工具,我们现在可以开始探索 PowerShell 的功能了。
问题
答案
第二题
第三题
Task4 Navigating the File System and Working with Files 导航文件系统和使用文件
图片版
文字版
PowerShell provides a range of cmdlets for navigating the file system and managing files, many of which have counterparts in the traditional Windows CLI.
PowerShell 提供了一系列用于导航文件系统和管理文件的 Cmdlet, 其中许多在传统 Windows CLI 中有对应的 Cmdlet。
Similar to the dir
command in Command Prompt (or ls
in Unix-like systems), Get-ChildItem
lists the files and directories in a location specified with the -Path
parameter. It can be used to explore directories and view their contents. If no Path
is specified, the cmdlet will display the content of the current working directory.
类似于命令提示符中的 dir 命令 (或类 UNIX 系统中的 ls),Get-ChildItem 在 - Path 参数指定的位置列出文件和工作目录。它可以用来探索目录并查看其内容。如果没有指定 Path,Cmdlet 将显示当前工作目录的内容。
Terminal终端
PS C:\Users\captain> Get-ChildItem Directory: C:\Users\captainMode LastWriteTime Length Name
---- ------------- ------ ----
d-r--- 5/8/2021 9:15 AM Desktop
d-r--- 9/4/2024 10:58 AM Documents
d-r--- 5/8/2021 9:15 AM Downloads
d-r--- 5/8/2021 9:15 AM Favorites
d-r--- 5/8/2021 9:15 AM Links
d-r--- 5/8/2021 9:15 AM Music
d-r--- 5/8/2021 9:15 AM Pictures
d----- 5/8/2021 9:15 AM Saved Games
d-r--- 5/8/2021 9:15 AM Videos
To navigate to a different directory, we can use the Set-Location
cmdlet. It changes the current directory, bringing us to the specified path, akin to the cd
command in Command Prompt.
要导航到不同的工作目录,可以使用 Set-Location cmdlet。它会更改工作目录,将我们带到指定的路径,类似于命令提示符中的 cd 命令。
Terminal终端
PS C:\Users\captain> Set-Location -Path ".\Documents"
PS C:\Users\captain\Documents>
While the traditional Windows CLI uses separate commands to create and manage different items like directories and files, PowerShell simplifies this process by providing a single set of cmdlets to handle the creation and management of both files and directories.
传统的 Windows CLI 使用单独的命令来创建和管理不同的项目,如目录和文件,而 PowerShell 通过提供一组 Cmdlet 来简化这个过程,以处理文件和目录的创建和管理。
To create an item in PowerShell, we can use New-Item
. We will need to specify the path of the item and its type (whether it is a file or a directory).
要在 PowerShell 中创建一个项目,可以使用 New-Item。我们需要指定项目的路径及其类型 (无论是文件还是目录)。
Terminal终端
PS C:\Users\captain\Documents> New-Item -Path ".\captain-cabin\captain-wardrobe" -ItemType "Directory"Directory: C:\Users\captain\Documents\captain-cabinMode LastWriteTime Length Name
---- ------------- ------ ----
d----- 9/4/2024 12:20 PM captain-wardrobePS C:\Users\captain\Documents> New-Item -Path ".\captain-cabin\captain-wardrobe\captain-boots.txt" -ItemType "File" Directory: C:\Users\captain\Documents\captain-cabin\captain-wardrobeMode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 9/4/2024 11:46 AM 0 captain-boots.txt
Similarly, the Remove-Item
cmdlet removes both directories and files, whereas in Windows CLI we have separate commands rmdir
and del
.
类似地,Remove-Item cmdlet 同时删除目录和文件,而在 Windows CLI 中,我们有单独的命令 rmdir 和 del。
Terminal终端
PS C:\Users\captain\Documents> Remove-Item -Path ".\captain-cabin\captain-wardrobe\captain-boots.txt"
PS C:\Users\captain\Documents> Remove-Item -Path ".\captain-cabin\captain-wardrobe"
We can copy or move files and directories alike, using respectively Copy-Item
(equivalent to copy
) and Move-Item
(equivalent to move
).
我们可以分别使用 Copy-Item (等效于复制) 和 Move-Item (等效于移动) 来复制或移动文件和目录。
Terminal终端
PS C:\Users\captain\Documents> Copy-Item -Path .\captain-cabin\captain-hat.txt -Destination .\captain-cabin\captain-hat2.txt
PS C:\Users\captain\Documents> Get-ChildItem -Path ".\captain-cabin\" Directory: C:\Users\captain\Documents\captain-cabinMode LastWriteTime Length Name
---- ------------- ------ ----
d----- 9/4/2024 12:50 PM captain-wardrobe
-a---- 9/4/2024 12:50 PM 0 captain-boots.txt
-a---- 9/4/2024 12:14 PM 264 captain-hat.txt
-a---- 9/4/2024 12:14 PM 264 captain-hat2.txt
-a---- 9/4/2024 12:37 PM 2116 ship-flag.txt
Finally, to read and display the contents of a file, we can use the Get-Content
cmdlet, which works similarly to the type
command in Command Prompt (or cat
in Unix-like systems).
最后,要读取和显示文件的内容,我们可以使用 Get-Content cmdlet, 它的工作方式类似于命令提示符 (或类 UNIX 系统中的 cat) 中的 type 命令。
Terminal终端
PS C:\Users\captain\Documents\captain-cabin> Get-Content -Path ".\captain-hat.txt"_ _
| | | |
| |__ __ _| |_
| '_ \ / _ | __|
| | | | (_| | |_
|_| |_|\__,_|\__|Don't touch my hat!
问题
答案
四个
指令小结
Navigating the File System and Working with Files
导航文件系统和使用文件
PowerShell offers cmdlets for file system management, similar to CMD or Linux but with a unified approach.
PowerShell 提供用于文件系统管理的 Cmdlet, 类似于 CMD 或 Linux, 但采用统一的方法。
Get-ChildItem (list directory contents) – like dir in CMD or ls in Linux.
Get-ChildItem (列出目录内容)—— 类似于 CMD 中的 dir 或 Linux 中的 ls。
Set-Location (navigate directories) – like cd in CMD/Linux.
设置位置 (导航目录)—— 如 CMD/Linux 中的 cd。
New-Item (create a file or directory) – similar to mkdir or touch.
New-Item (创建文件或目录)—— 类似于 mkdir 或 touch。
Remove-Item (delete file/directory) – like del or rmdir in CMD.
Remove-Item (删除文件 / 目录)—— 类似于 CMD 中的 del 或 rmdir。
Get-Content (read file content) – similar to type in CMD and cat in Linux.
Get-Content (读取文件内容)—— 类似于 Linux 中 CMD 中的 type 和 cat。
Task5 Piping, Filtering, and Sorting Data 管道、过滤和数据排序
图片版
文字版
Piping is a technique used in command-line environments that allows the output of one command to be used as the input for another. This creates a sequence of operations where the data flows from one command to the next. Represented by the |
symbol, piping is widely used in the Windows CLI, as introduced earlier in this module, as well as in Unix-based shells.
管道是一种用于命令行环境的技术,它允许一个命令的输出作为另一个命令的输入。这创建了一个操作序列,其中数据从一个命令流向下一个命令。由 | 符号表示,管道在 Windows CLI 中被广泛使用,正如本模块前面介绍的那样,以及在基于 Unix 的 shell 中。
In PowerShell, piping is even more powerful because it passes objects rather than just text. These objects carry not only the data but also the properties and methods that describe and interact with the data.
在 PowerShell 中,管道甚至更加强大,因为它传递的是对象,而不仅仅是文本。这些对象不仅携带数据,还包含描述和与数据交互的属性和方法。
For example, if you want to get a list of files in a directory and then sort them by size, you could use the following command in PowerShell:
例如,如果你想获取目录中文件的列表,然后按大小对它们进行排序,可以在 PowerShell 中使用以下命令:
Terminal终端
PS C:\Users\captain\Documents\captain-cabin> Get-ChildItem | Sort-Object LengthDirectory: C:\Users\captain\Documents\captain-cabinMode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 9/4/2024 12:50 PM 0 captain-boots.txt
-a---- 9/4/2024 12:14 PM 264 captain-hat2.txt
-a---- 9/4/2024 12:14 PM 264 captain-hat.txt
-a---- 9/4/2024 12:37 PM 2116 ship-flag.txt
d----- 9/4/2024 12:50 PM captain-wardrobe
Here, Get-ChildItem
retrieves the files (as objects), and the pipe (|
) sends those file objects to Sort-Object
, which then sorts them by their Length
(size) property. This object-based approach allows for more detailed and flexible command sequences.
在这里,Get-ChildItem 检索文件 (作为对象), 管道 (|) 将这些文件对象发送到 Sort-Object, 后者随后根据它们的 Length (size) 属性对它们进行排序。这种基于对象的方法允许更详细和灵活的命令序列。
In the example above, we have leveraged the Sort-Object
cmdlet to sort objects based on specified properties. Beyond sorting, PowerShell provides a set of cmdlets that, when combined with piping, allow for advanced data manipulation and analysis.
在上面的示例中,我们利用 Sort-Object cmdlet 根据指定的属性对对象进行排序。除了排序之外,PowerShell 还提供了一组 cmdlet, 当与管道相结合时,可以进行高级的数据操作和分析。
To filter objects based on specified conditions, returning only those that meet the criteria, we can use the Where-Object
cmdlet. For instance, to list only .txt
files in a directory, we can use:
要根据指定条件过滤对象,只返回符合条件的对象,可以使用 Where-Object cmdlet。例如,要在目录中仅列出.txt 文件,可以使用:
Terminal终端
PS C:\Users\captain\Documents\captain-cabin> Get-ChildItem | Where-Object -Property "Extension" -eq ".txt" Directory: C:\Users\captain\Documents\captain-cabinMode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 9/4/2024 12:50 PM 0 captain-boots.txt
-a---- 9/4/2024 12:14 PM 264 captain-hat.txt
-a---- 9/4/2024 12:14 PM 264 captain-hat2.txt
-a---- 9/4/2024 12:37 PM 2116 ship-flag.txt
Here, Where-Object
filters the files by their Extension
property, ensuring that only files with extension equal (-eq
) to .txt
are listed.
在这里,Where-Object 根据文件的 Extension 属性过滤文件,确保只列出扩展名等于 (-eq).txt 的文件。
The operator -eq
(i.e. "equal to") is part of a set of comparison operators that are shared with other scripting languages (e.g. Bash, Python). To show the potentiality of the PowerShell's filtering, we have selected some of the most useful operators from that list:
运算符 - eq (即 “equal to”) 是一组与其他脚本语言 (例如 Bash、Python) 共享的比较运算符的一部分。为了展示 PowerShell 过滤的潜力,我们从列表中选择了一些最有用的运算符:
-ne
: "not equal". This operator can be used to exclude objects from the results based on specified criteria.
-ne:“不等于”。这个运算符可以用来根据指定的标准从结果中排除对象。-gt
: "greater than". This operator will filter only objects which exceed a specified value. It is important to note that this is a strict comparison, meaning that objects that are equal to the specified value will be excluded from the results.
-gt:“大于”。这个运算符只会过滤超过指定值的对象。需要注意的是,这是一个严格的比较,意味着等于指定值的对象将被排除在结果之外。-ge
: "greater than or equal to". This is the non-strict version of the previous operator. A combination of-gt
and-eq
.
-ge:“大于或等于”。这是前一个运算符的非严格版本。-gt 和 - eq 的组合。-lt
: "less than". Like its counterpart, "greater than", this is a strict operator. It will include only objects which are strictly below a certain value.
-lt:“小于”。与其对应的 “大于” 一样,这是一个严格的运算符。它将只包括严格小于某个特定值的对象。-le
: "less than or equal to". Just like its counterpart-ge
, this is the non-strict version of the previous operator. A combination of-lt
and-eq
.
-le:“小于或等于”。与其对应的 - ge 一样,这是前一个运算符的非严格版本。它是 - lt 和 - eq 的组合。
Below, another example shows that objects can also be filtered by selecting properties that match (-like
) a specified pattern:
下面的另一个例子表明,也可以通过选择与指定模式匹配 (-like) 的属性来过滤对象:
Terminal终端
PS C:\Users\captain\Documents\captain-cabin> Get-ChildItem | Where-Object -Property "Name" -like "ship*" Directory: C:\Users\captain\Documents\captain-cabinMode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 9/4/2024 12:37 PM 2116 ship-flag.txt
The next filtering cmdlet, Select-Object
, is used to select specific properties from objects or limit the number of objects returned. It’s useful for refining the output to show only the details one needs.
下一个过滤 cmdlet Select-Object 用于从对象中选择特定属性或限制返回的对象数量。它有助于微调输出,以仅显示所需的细节。
Terminal终端
PS C:\Users\captain\Documents\captain-cabin> Get-ChildItem | Select-Object Name,Length Name Length
---- ------
captain-wardrobe
captain-boots.txt 0
captain-hat.txt 264
captain-hat2.txt 264
ship-flag.txt 2116
The cmdlets pipeline can be extended by adding more commands, as the feature isn’t limited to just piping between two cmdlets. As an exercise, try and build a pipeline of cmdlets to sort and filter the output with the goal of displaying the largest file in the C:\Users\captain\Documents\captain-cabin
directory.
Cmdlet 管道可以通过添加更多命令来扩展,因为该功能不仅限于在两个 cmdlet 之间进行管道。作为一个练习,尝试构建一个 cmdlet 管道来对输出进行排序和过滤,目标是显示 C:UserscaptainDocumentscaptain-cabin 目录中最大的文件。
Click here to look at a possible solution. Don’t cheat!
点击这里查看一个可能的解决方案。别作弊!
Get-ChildItem | Sort-Object Length -Descending | Select-Object -First 1Directory: C:\Users\captain\Documents\captain-cabinMode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 9/4/2024 12:37 PM 2116 ship-flag.txt
The last in this set of filtering cmdlets is Select-String
. This cmdlet searches for text patterns within files, similar to grep
in Unix-based systems or findstr
in Windows Command Prompt. It’s commonly used for finding specific content within log files or documents.
这组过滤 cmdlet 中的最后一个是 Select-String。这个 cmdlet 在文件中搜索文本模式,类似于 Unix 系统中的 grep 或 Windows 命令提示符中的 findstr。它通常用于在日志文件或文档中查找特定内容。
Terminal终端
PS C:\Users\captain\Documents\captain-cabin> Select-String -Path ".\captain-hat.txt" -Pattern "hat" captain-hat.txt:8:Don't touch my hat!
The Select-String
cmdlet fully supports the use of regular expressions (regex). This advanced feature allows for complex pattern matching within files, making it a powerful tool for searching and analysing text data.
Select-String cmdlet 完全支持使用正则表达式 (regex)。这个高级功能允许在文件内进行复杂的模式匹配,使其成为搜索和分析文本数据的强大工具。
Task6 System and Network Information 系统和网络信息
图片版
文字版
PowerShell was created to address a growing need for a powerful automation and management tool to help system administrators and IT professionals. As such, it offers a range of cmdlets that allow the retrieval of detailed information about system configuration and network settings.
PowerShell 的创建旨在满足日益增长的对强大自动化和管理工具的需求,以帮助系统管理员和 IT 专业人员。因此,它提供了一系列 Cmdlet, 允许检索有关系统配置和网络设置的详细信息。
The Get-ComputerInfo
cmdlet retrieves comprehensive system information, including operating system information, hardware specifications, BIOS details, and more. It provides a snapshot of the entire system configuration in a single command. Its traditional counterpart systeminfo
retrieves only a small set of the same details.
Get-ComputerInfo cmdlet 检索全面的系统信息,包括操作系统信息、硬件规格、BIOS 详细信息等。它在单个命令中提供整个系统配置的快照。其传统对应的 systeminfo 只检索一小部分相同的详细信息。
Terminal终端
PS C:\Users\captain> Get-ComputerInfoWindowsBuildLabEx : 20348.859.amd64fre.fe_release_svc_prod2.220707-1832
WindowsCurrentVersion : 6.3
WindowsEditionId : ServerDatacenter
WindowsInstallationType : Server Core
WindowsInstallDateFromRegistry : 4/23/2024 6:36:29 PM
WindowsProductId : 00454-60000-00001-AA763
WindowsProductName : Windows Server 2022 Datacenter
[...]
Essential for managing user accounts and understanding the machine’s security configuration, Get-LocalUser
lists all the local user accounts on the system. The default output displays, for each user, username, account status, and description.
对于管理用户账户和理解机器的安全配置至关重要,Get-LocalUser 列出了系统上的所有本地用户账户。默认输出显示每个用户的用户名、账户状态和描述。
Terminal终端
PS C:\Users\captain> Get-LocalUserName Enabled Description
---- ------- -----------
Administrator True Built-in account for administering the computer/domain
captain True The beloved captain of this pirate ship.
DefaultAccount False A user account managed by the system.
Guest False Built-in account for guest access to the computer/domain
WDAGUtilityAccount False A user account managed and used by the system for Windows Defender Application Guard scenarios.
Similar to the traditional ipconfig
command, the following two cmdlets can be used to retrieve detailed information about the system’s network configuration.
与传统的 ipconfig 命令类似,以下两个 cmdlet 可用于检索有关系统网络配置的详细信息。
Get-NetIPConfiguration
provides detailed information about the network interfaces on the system, including IP addresses, DNS servers, and gateway configurations.
Get-NetIPConfiguration 提供了关于系统上网络接口的详细信息,包括 IP 地址、DNS 服务器和网关配置。
Terminal终端
PS C:\Users\captain> Get-NetIPConfigurationInterfaceAlias : Ethernet
InterfaceIndex : 5
InterfaceDescription : Amazon Elastic Network Adapter
NetProfile.Name : Network 3
IPv4Address : 10.10.178.209
IPv6DefaultGateway :
IPv4DefaultGateway : 10.10.0.1
DNSServer : 10.0.0.2
In case we need specific details about the IP addresses assigned to the network interfaces, the Get-NetIPAddress
cmdlet will show details for all IP addresses configured on the system, including those that are not currently active.
如果我们需要关于分配给网络接口的 IP 地址的具体详细信息,Get-NetIPAddress cmdlet 将显示系统上配置的所有 IP 地址的详细信息,包括那些当前未处于活动状态的 IP 地址。
Terminal终端
PS C:\Users\captain> Get-NetIPAddressIPAddress : fe80::3fef:360c:304:64e%5
InterfaceIndex : 5
InterfaceAlias : Ethernet
AddressFamily : IPv6
Type : Unicast
PrefixLength : 64
PrefixOrigin : WellKnown
SuffixOrigin : Link
AddressState : Preferred
ValidLifetime : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource : False
PolicyStore : ActiveStoreIPAddress : ::1
InterfaceIndex : 1
InterfaceAlias : Loopback Pseudo-Interface 1
AddressFamily : IPv6
[...]IPAddress : 10.10.178.209
InterfaceIndex : 5
InterfaceAlias : Ethernet
AddressFamily : IPv4
[...]IPAddress : 127.0.0.1
InterfaceIndex : 1
InterfaceAlias : Loopback Pseudo-Interface 1
AddressFamily : IPv4
[...]
These cmdlets give IT professionals the ability to quickly access crucial system and network information directly from the command line, making it easier to monitor and manage both local and remote machines.
这些 Cmdlets 使 IT 专业人员能够直接从命令行快速访问关键的系统和网络信息,使监控和管理本地和远程机器变得更加容易。
问题
答案
第一题
第二题
第三题 思路进入该用户的文件夹寻找
Task7 Real-Time System Analysis 实时系统分析
图片版
文字版
To gather more advanced system information, especially concerning dynamic aspects like running processes, services, and active network connections, we can leverage a set of cmdlets that go beyond static machine details.
为了收集更高级的系统信息,特别是关于运行进程、服务和活动网络连接等动态方面的信息,我们可以利用一组超越静态机器细节的 Cmdlet。
Get-Process
provides a detailed view of all currently running processes, including CPU and memory usage, making it a powerful tool for monitoring and troubleshooting.
Get-Process 提供了所有当前运行进程的详细视图,包括 CPU 和内存使用情况,使其成为监控和故障排除的强大工具。
Terminal终端
PS C:\Users\captain> Get-ProcessHandles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------67 5 872 500 0.06 2340 0 AggregatorHost55 5 712 2672 0.02 3024 0 AM_Delta_Patch_1.417.483.0309 13 18312 1256 0.52 1524 0 amazon-ssm-agent78 6 4440 944 0.02 516 0 cmd94 7 1224 1744 0.31 568 0 conhost
[...]
Similarly, Get-Service
allows the retrieval of information about the status of services on the machine, such as which services are running, stopped, or paused. It is used extensively in troubleshooting by system administrators, but also by forensics analysts hunting for anomalous services installed on the system.
类似地,Get-Service 允许检索机器上服务状态的信息,例如哪些服务正在运行、停止或暂停。它被系统管理员广泛用于故障排除,也被取证分析师用于寻找安装在系统上的异常服务。
Terminal终端
PS C:\Users\captain> Get-ServiceStatus Name DisplayName
------ ---- -----------
Stopped Amazon EC2Launch Amazon EC2Launch
Running AmazonSSMAgent Amazon SSM Agent
Stopped AppIDSvc Application Identity
Running BFE Base Filtering Engine
Running CertPropSvc Certificate Propagation
Stopped ClipSVC Client License Service (ClipSVC)
[...]
To monitor active network connections, Get-NetTCPConnection
displays current TCP connections, giving insights into both local and remote endpoints. This cmdlet is particularly handy during an incident response or malware analysis task, as it can uncover hidden backdoors or established connections towards an attacker-controlled server.
为了监控活跃的网络连接,Get-NetTCPConnection 显示当前 TCP 连接,为本地和远程端点提供洞察。这个 Cmdlet 在事件响应或恶意软件分析任务中特别方便,因为它可以发现隐藏的后门或与攻击者控制的服务器建立的连接。
Terminal终端
PS C:\Users\captain> Get-NetTCPConnectionLocalAddress LocalPort RemoteAddress RemotePort State AppliedSetting OwningProcess
------------ --------- ------------- ---------- ----- -------------- -------------
[...]
:: 22 :: 0 Listen 1444
10.10.178.209 49695 199.232.26.172 80 TimeWait 0
0.0.0.0 49668 0.0.0.0 0 Listen 424
0.0.0.0 49667 0.0.0.0 0 Listen 652
0.0.0.0 49666 0.0.0.0 0 Listen 388
0.0.0.0 49665 0.0.0.0 0 Listen 560
0.0.0.0 49664 0.0.0.0 0 Listen 672
0.0.0.0 3389 0.0.0.0 0 Listen 980
10.10.178.209 139 0.0.0.0 0 Listen 4
0.0.0.0 135 0.0.0.0 0 Listen 908
10.10.178.209 22 10.14.87.60 53523 Established Internet 1444
0.0.0.0 22 0.0.0.0 0 Listen 1444
Additionally, we are going to mention Get-FileHash
as a useful cmdlet for generating file hashes, which is particularly valuable in incident response, threat hunting, and malware analysis, as it helps verify file integrity and detect potential tampering.
此外,我们将提到 Get-FileHash 作为一个用于生成文件哈希的有用 Cmdlet, 它在事件响应、威胁猎杀和恶意软件分析中特别有价值,因为它有助于验证文件完整性并检测潜在的篡改。
Terminal终端
PS C:\Users\captain\Documents\captain-cabin> Get-FileHash -Path .\ship-flag.txt Algorithm Hash Path
--------- ---- ----
SHA256 54D2EC3C12BF3D[...] C:\Users\captain\Documents\captain-cabin\ship-flag.txt
These cmdlets collectively provide a comprehensive set of tools for real-time system monitoring and analysis, proving especially useful to incident responders and threat hunters.
这些 Cmdlet 共同提供了一套全面的实时系统监控和分析工具,对事件响应者和威胁猎杀者特别有用。
问题
答案
第一题
第二题
第三题
利用管道符
先把获取服务的内容通过管道传到 where-object(让他寻找)寻找大括号里面的筛选条件 寻找到之后 将内容通过管道传到选择对象里面 列举出服务名字 和 displayname
Task8 Scripting 脚本编写
图片版
Let us discover some example usage for this powerful cmdlet by consulting the Get-Help
"examples" page:
让我们通过查看 Get-Help “示例” 页面来发现这个功能强大的 Cmdlet 的一些示例用法:
Terminal终端
PS C:\Users\captain> Get-Help Invoke-Command -examplesNAMEInvoke-CommandSYNOPSISRuns commands on local and remote computers.------------- Example 1: Run a script on a server -------------Invoke-Command -FilePath c:\scripts\test.ps1 -ComputerName Server01The FilePath parameter specifies a script that is located on the local computer. The script runs on the remote computer and the results are returned to the local computer.--------- Example 2: Run a command on a remote server ---------Invoke-Command -ComputerName Server01 -Credential Domain01\User01 -ScriptBlock { Get-Culture }The ComputerName parameter specifies the name of the remote computer. The Credential parameter is used to run the command in the security context of Domain01\User01, a user who has permission to run commands. The ScriptBlock parameter specifies the command to be run on the remote computer.In response, PowerShell requests the password and an authentication method for the User01 account. It then runs the command on the Server01 computer and returns the result.
[...]
文字版
Scripting is the process of writing and executing a series of commands contained in a text file, known as a script, to automate tasks that one would generally perform manually in a shell, like PowerShell.
脚本化是指编写和执行一系列包含在文本文件中的命令的过程,这些命令被称为脚本,用于自动执行通常需要在 shell (如 PowerShell) 中手动执行的任务。
Simply speaking, scripting is like giving a computer a to-do list, where each line in the script is a task that the computer will carry out automatically. This saves time, reduces the chance of errors, and allows to perform tasks that are too complex or tedious to do manually. As you learn more about shells and scripting, you’ll discover that scripts can be powerful tools for managing systems, processing data, and much more.
简单来说,脚本编写就像给计算机一个待办事项清单,其中脚本中的每一行都是计算机将自动执行的任务。这样可以节省时间,减少出错的可能性,并允许执行手动执行过于复杂或繁琐的任务。随着你对 shell 和脚本编写的了解越来越深入,你会发现脚本可以成为管理系统、处理数据等诸多方面的强大工具。
Learning scripting with PowerShell goes beyond the scope of this room. Nonetheless, we must understand that its power makes it a crucial skill across all cyber security roles.
使用 PowerShell 学习脚本编写超出了这个房间的范围。尽管如此,我们必须理解,它的强大功能使其成为所有网络安全角色的关键技能。
- For blue team professionals such as incident responders, malware analysts, and threat hunters, PowerShell scripts can automate many different tasks, including log analysis, detecting anomalies, and extracting indicators of compromise (IOCs). These scripts can also be used to reverse-engineer malicious code (malware) or automate the scanning of systems for signs of intrusion.
对于蓝队专业人员,如事件响应人员、恶意软件分析人员和威胁猎杀者,PowerShell 脚本可以自动执行许多不同的任务,包括日志分析、检测异常和提取泄露指标 (IOCs)。这些脚本还可以用于反向工程恶意代码 (恶意软件), 或自动扫描系统以寻找入侵迹象。 - For the red team, including penetration testers and ethical hackers, PowerShell scripts can automate tasks like system enumeration, executing remote commands, and crafting obfuscated scripts to bypass defences. Its deep integration with all types of systems makes it a powerful tool for simulating attacks and testing systems’ resilience against real-world threats.
对于红队,包括渗透测试人员和道德黑客,PowerShell 脚本可以自动执行系统枚举、执行远程命令以及编写混淆脚本以绕过防御等任务。它与所有类型系统的深度集成使其成为模拟攻击和测试系统抵御现实世界威胁弹性的强大工具。 - Staying in the context of cyber security, system administrators benefit from PowerShell scripting for automating integrity checks, managing system configurations, and securing networks, especially in remote or large-scale environments. PowerShell scripts can be designed to enforce security policies, monitor systems health, and respond automatically to security incidents, thus enhancing the overall security posture.
在网络安全背景下,系统管理员可以从 PowerShell 脚本中受益,这些脚本可以自动执行完整性检查、管理系统配置和保护网络,特别是在远程或大规模环境中。PowerShell 脚本可以设计用于执行安全策略、监控系统运行状况,并自动响应安全事件,从而提高整体安全态势。
Whether used defensively or offensively, PowerShell scripting is an essential capability in the cyber security toolkit.
无论是用于防御还是攻击,PowerShell 脚本都是网络安全工具包中不可或缺的功能。
Before concluding this task about scripting, we can’t go without mentioning the Invoke-Command
cmdlet.
在结束这个关于脚本的任务之前,我们不能不提到 Invoke-Command cmdlet。
Invoke-Command
is essential for executing commands on remote systems, making it fundamental for system administrators, security engineers and penetration testers. Invoke-Command
enables efficient remote management and—combining it with scripting—automation of tasks across multiple machines. It can also be used to execute payloads or commands on target systems during an engagement by penetration testers—or attackers alike.
Invoke-Command 对于在远程系统上执行命令至关重要,这使得它对系统管理员、安全工程师和渗透测试人员至关重要。Invoke-Command 可以实现高效的远程管理,并将其与跨多台机器的任务脚本自动化相结合。它还可以用于在渗透测试人员或攻击者的交战期间,在目标系统上执行有效负载或命令。
Let us discover some example usage for this powerful cmdlet by consulting the Get-Help
"examples" page:
让我们通过查看 Get-Help “示例” 页面来发现这个功能强大的 Cmdlet 的一些示例用法:
Terminal终端
PS C:\Users\captain> Get-Help Invoke-Command -examplesNAMEInvoke-CommandSYNOPSISRuns commands on local and remote computers.------------- Example 1: Run a script on a server -------------Invoke-Command -FilePath c:\scripts\test.ps1 -ComputerName Server01The FilePath parameter specifies a script that is located on the local computer. The script runs on the remote computer and the results are returned to the local computer.--------- Example 2: Run a command on a remote server ---------Invoke-Command -ComputerName Server01 -Credential Domain01\User01 -ScriptBlock { Get-Culture }The ComputerName parameter specifies the name of the remote computer. The Credential parameter is used to run the command in the security context of Domain01\User01, a user who has permission to run commands. The ScriptBlock parameter specifies the command to be run on the remote computer.In response, PowerShell requests the password and an authentication method for the User01 account. It then runs the command on the Server01 computer and returns the result.
[...]
两个示例翻译
示例 1: 在服务器上运行脚本
Invoke-Command -FilePath c:scriptstest.ps1 -ComputerName Server01
FilePath 参数指定位于本地计算机上的脚本。该脚本在远程计算机上运行,并将结果返回到本地计算机。
示例 2: 在远程服务器上运行命令
Invoke-Command -ComputerName Server01 -Credential Domain01User01 -ScriptBlock { Get-Culture }
ComputerName 参数指定远程计算机的名称。Credential 参数用于在 Domain01User01 的安全上下文中运行命令,该用户具有运行命令的权限。ScriptBlock 参数指定要在远程计算机上运行的命令。
作为响应,PowerShell 请求 User01 帐户的密码和身份验证方法。然后,它在 Server01 计算机上运行命令并返回结果。
The first two examples provided by the Get-Help
"examples" page and reported above are enough to grasp the simplicity and power of the Invoke-Command
cmdlet.
Get-Help “示例” 页面提供的前两个示例以及上面报告的内容足以让我们理解 Invoke-Command cmdlet 的简单性和强大功能。
The first example shows how the cmdlet can be very easily combined with any custom script to automate tasks on remote computers.
第一个例子展示了如何非常容易地将 cmdlet 与任何自定义脚本结合起来,以在远程计算机上自动执行任务。
The second example demonstrates that we don't need to know how to script to benefit from the power of Invoke-Command
. In fact, by appending the -ScriptBlock { ... }
parameter to the cmdlet's syntax, we can execute any command (or sequence of commands) on the remote computer. The result would be the same as if we were typing the commands in a local PowerShell session on the remote computer itself.
第二个例子表明,我们不需要知道如何编写脚本就能从 Invoke-Command 的强大功能中受益。事实上,通过将 - ScriptBlock {...} 参数添加到 cmdlet 的语法中,我们可以在远程计算机上执行任何命令 (或命令序列)。结果将与我们在远程计算机本地 PowerShell 会话中输入命令相同。
Task9 Conclusion结论 指令小结
指令小结
Get-Content
(read file content) – similar totype
in CMD andcat
in Linux.
Get-Content (读取文件内容)—— 类似于 CMD 中的 type 和 Linux 中的 cat。Set-Location
(change directory) – similar tocd
in CMD/Linux.
Set-Location (更改目录)—— 类似于 CMD/Linux 中的 cd。Get-Command
(list all commands) – helps discover available cmdlets.
Get-Command (列出所有命令)- 帮助发现可用的 cmdlet
文件管理
Get-ChildItem
(list directory contents) – likedir
in CMD orls
in Linux.
Get-ChildItem (列出目录内容)—— 类似于 CMD 中的 dir 或 Linux 中的 ls。Set-Location
(navigate directories) – likecd
in CMD/Linux.
Set-Location (导航目录)—— 类似于 CMD/Linux 中的 cd。New-Item
(create a file or directory) – similar tomkdir
ortouch
.
New-Item (创建文件或目录)—— 类似于 mkdir 或 touch。Remove-Item
(delete file/directory) – likedel
orrmdir
in CMD.
Remove-Item (删除文件 / 目录)—— 类似于 CMD 中的 del 或 rmdir。Get-Content
(read file content) – similar totype
in CMD andcat
in Linux.
Get-Content (读取文件内容)—— 类似于 CMD 中的 type 和 Linux 中的 cat。
管道
Sort-Object
(sorts objects by property) – no direct CMD equivalent, similar tosort
in Linux.
Sort-Object (按属性对对象进行排序)—— 没有直接的 CMD 等价物,类似于 Linux 中的 sort。Where-Object
(filter objects based on conditions) – similar togrep
in Linux.
Where-Object (基于条件筛选对象)—— 类似于 Linux 中的 grep。Select-Object
(select properties from objects) – used for refining output.
Select-Object (从对象中选择属性)—— 用于细化输出。
运算符
-ne
: "not equal". This operator can be used to exclude objects from the results based on specified criteria.
-ne:“不等于”。这个运算符可以用来根据指定的标准从结果中排除对象。-gt
: "greater than". This operator will filter only objects which exceed a specified value. It is important to note that this is a strict comparison, meaning that objects that are equal to the specified value will be excluded from the results.
-gt:“大于”。这个运算符只会过滤超过指定值的对象。需要注意的是,这是一个严格的比较,意味着等于指定值的对象将被排除在结果之外。-ge
: "greater than or equal to". This is the non-strict version of the previous operator. A combination of-gt
and-eq
.
-ge:“大于或等于”。这是前一个运算符的非严格版本。-gt 和 - eq 的组合。-lt
: "less than". Like its counterpart, "greater than", this is a strict operator. It will include only objects which are strictly below a certain value.
-lt:“小于”。与其对应的 “大于” 一样,这是一个严格的运算符。它只包含严格小于某个值的对象。-le
: "less than or equal to". Just like its counterpart-ge
, this is the non-strict version of the previous operator. A combination of-lt
and-eq
.
-le:“小于或等于”。与其对应的 - ge 一样,这是前一个运算符的非严格版本。-lt 和 - eq 的组合。
系统和网络信息
Get-ComputerInfo
: Retrieves detailed system information (likesysteminfo
in CMD).
Get-ComputerInfo: 检索详细的系统信息 (类似于 CMD 中的 systeminfo)。Get-NetIPConfiguration
: Shows network interface details (similar toipconfig
in CMD).
Get-NetIPConfiguration: 显示网络接口细节 (类似于 CMD 中的 ipconfig)。Get-LocalUser
: Lists local user accounts (similar tonet user
in CMD).
Get-LocalUser: 列出本地用户帐户 (类似于 CMD 中的网络用户)。
实时系统分析
Get-Process
: Lists running processes (similar totasklist
in CMD).
Get-Process: 列出正在运行的进程 (类似于 CMD 中的任务列表)。Get-Service
: Shows services and their statuses (similar tonet start
in CMD).
Get-Service: 显示服务及其状态 (类似于 CMD 中的净启动)。Get-NetTCPConnection
: Displays active TCP connections (likenetstat
in CMD).
Get-NetTCPConnect: 显示活跃的 TCP 连接 (类似于 CMD 中的 netstat)