当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell 写入输出:您友好的输出伴侣

作者:精品下载站 日期:2024-12-14 13:12:31 浏览:13 分类:玩电脑

PowerShell 写入输出:您友好的输出伴侣


告别沉闷、可预测的脚本输出!使用 PowerShell Write-Output cmdlet,您可以为 PowerShell 脚本添加创意和个性。

Write-Output cmdlet 是一个功能强大的工具,是满足您所有自动化和系统管理需求的完美伴侣。在本教程中,您将学习如何最大限度地发挥 Write-Output cmdlet 的潜力。

准备好?继续阅读并发现 Write-Output cmdlet 的魔力!

先决条件

本教程将是一个实践演示。要继续操作,请确保您的计算机安装了 PowerShell(最好是最新版本)。本教程使用安装了 PowerShell 7 的 Windows 10。

将对象输出到控制台

PowerShell Write-Output cmdlet 将对象写入输出流,并在控制台中显示命令或消息的输出。但您会惊讶地发现这个工具如何使输出更有意义和更有价值。

使用 Write-Output cmdlet 自定义输出,而不是在控制台中显示输出。 Write-Output cmdlet 可以输出任何对象或数据类型,例如字符串、整数、数组,甚至复杂对象。

运行以下命令将 Hello, World! 消息输出到控制台。

Write-Output "Hello, World!”

下面,您可以看到 Write-Output cmdlet 的最基本功能。但请继续阅读以了解此 cmdlet 的更多中级到高级用法。

[玩转系统] PowerShell 写入输出:您友好的输出伴侣

将对象传递给另一个命令

除了在控制台中显示输出之外,您还可以使用 Write-Output 命令将对象发送到另一个命令以进行进一步处理。如何?通过使用管道运算符 (|)。流水线使 Write-Output 成为用于自动化和系统管理任务的方便且多功能的命令。

假设您希望查看哪个进程消耗了大部分资源,例如 CPU。

运行以下命令以执行以下操作:

  • 检索系统上运行的所有进程 (Get-Process) 的列表。
  • 将列表输出到管道,然后传递给 Sort-Object 命令。管道运算符允许您将多个命令链接在一起,并将一个命令的输出处理为另一个命令的输入。
  • CPU 使用情况按-降序 顺序对进程列表 (Sort-Object) 进行排序。
$processes = Get-Process
Write-Output $processes | Sort-Object CPU -Descending

请注意,您可以将本教程中的任何命令放入 PowerShell 脚本中并运行它。

排序后的列表显示在控制台中,如下所示。

[玩转系统] PowerShell 写入输出:您友好的输出伴侣

以自定义格式输出对象

您已经了解了 Write-Output cmdlet 的基本输出格式,它工作得很好。但如果您愿意,您还可以使用自定义格式输出对象以添加个人风格。当您希望显示特定对象属性或自定义输出的外观时,自定义格式会很有用。

要输出具有自定义格式的对象,可以将 Format-CustomWrite-Output cmdlet 结合使用,如下所示:

创建自定义输出格式,然后将 Format-Custom cmdlet 的输出通过管道传输到 Write-Output。

运行以下命令,该命令不会产生输出,而是创建一个对象(哈希表),其中包含三个属性以及要输出的相应值。

$object = [pscustomobject]@{
Property1 = "Value1"
Property2 = "Value2"
Property3 = "Value3"
}

现在,运行以下命令来执行以下操作:

  • 为哈希表 ($object) 的输出 (Write-Output) 创建自定义格式 (Format-Table)。 Property1Property2Property3 属性设置为列。
  • 调整列宽 (-AutoSize) 以适合内容。
$object | Format-Table -Property Property1, Property2, Property3 -AutoSize | Write-Output

[玩转系统] PowerShell 写入输出:您友好的输出伴侣

或者,您可以将 Format-List cmdlet 与 Write-Output 结合使用,将对象输出为属性值对列表。

$object | Format-List -Property Property1, Property2, Property3 | Write-Output

[玩转系统] PowerShell 写入输出:您友好的输出伴侣

将集合对象作为单个实体传递

默认情况下,Write-Output 通过管道分别发送每个集合元素,这个过程称为枚举。但是您可以通过附加 -NoEnumerate 参数来防止此行为,将整个集合对象作为单个实体传递。

要了解 -NoEnumerate 参数的工作原理,请执行以下步骤:

运行以下命令以执行以下操作:

  • 声明一个从 1 到 3 的 $numbers 数组 (1,2,3)。
  • 计算通过管道的对象 (Measure-Object) 数量。
  • 输出对象测量值(Write-Output $numbers)。

如果没有 NoEnumerate 参数,Measure-Object 将返回 3 的计数 (3),因为 $numbers 的每个元素code> 数组被枚举并通过管道单独传递。

# Declares an Array
$numbers = 1,2,3
# Outputs the object count passed through the pipeline
Write-Output $numbers | Measure-Object

[玩转系统] PowerShell 写入输出:您友好的输出伴侣

现在,运行以下命令来输出通过管道传递的对象的计数。

但由于您附加了 -NoEnumerate 参数,Measure-Object cmdlet 会将对象视为单个实体,返回计数 1 (1 )。

# Declares an Array
$numbers = 1,2,3
# Outputs the object count as a single entity passed through the pipeline
Write-Output -NoEnumerate $numbers | Measure-Object

[玩转系统] PowerShell 写入输出:您友好的输出伴侣

Write-Output 命令括在括号中(即 (Write-Output 1,2,3))将强制进行枚举,而不管 -NoEnumerate 参数。

创建菜单系统和输入提示

Write-Output cmdlet 的另一个出色用途是使用提示用户输入的 PowerShell 脚本创建菜单系统。

使用您喜欢的文本/代码编辑器创建 .ps1 文件,填充下面的代码,然后保存文件。您可以根据需要命名该文件,但本教程的选择是 myoutput.ps1

下面的代码使用循环不断提示用户从选项列表中选择一个选项,直到用户选择“退出”选项。

# Initialize the $exit variable to $false
$exit = $false

# Start a loop that will run until the user selects the "Exit" option
while (!$exit) {

  # Display a list of options to the user
  Write-Output "Please select from the following options:"
  Write-Output "1. Option 1"
  Write-Output "2. Option 2"
  Write-Output "3. Option 3"
  Write-Output "4. Exit"

  # Prompt the user for a selection
  $selection = Read-Host

  # Use a switch statement to execute different codes based on the user's selection
  switch ($selection) {
    1 {
      # If the user selects option 1, display a message and do something for option 1
      Write-Output "You selected Option 1."
      # Do something for option 1
    }
    2 {
      # If the user selects option 2, display a message and do something for option 2
      Write-Output "You selected Option 2."
      # Do something for option 2
    }
    3 {
      # If the user selects option 3, display a message and do something for option 3
      Write-Output "You selected Option 3."
      # Do something for option 3
    }
    4 {
      # If the user selects option 4, set $exit to $true to exit the loop
      $exit = $true
    }
  }
}

现在,从工作目录运行脚本 (myoutput.ps1)。

./myoutput.ps1

如下所示,当您选择选项123时,将显示与您的选择相关的消息。但是当您选择选项4时,脚本将终止。

[玩转系统] PowerShell 写入输出:您友好的输出伴侣

显示启动屏幕或欢迎消息

除了列出用户可以选择的选项之外,您还可以使用 Write-Output 显示启动屏幕或欢迎消息。精美的启动画面会给您的脚本留下良好的印象(专业且精美)。

myoutput.ps1 文件中的代码替换为下面的代码,该代码会在运行脚本时输出启动屏幕(欢迎消息的横幅)。

您可以通过修改横幅的文本和格式来自定义启动屏幕。您可以根据需要向启动屏幕添加其他元素,例如徽标或文本。

# Clear the screen
Clear-Host

# Display the splash screen using Write-Output
Write-Output "##############################################"
Write-Output "#                                            #"
Write-Output "#   Welcome to the SuperScript 3000!         #"
Write-Output "#                                            #"
Write-Output "##############################################"

现在,运行脚本并查看启动屏幕的外观。

./myoutput.ps1

[玩转系统] PowerShell 写入输出:您友好的输出伴侣

显示进度条

运行脚本时,进度指示器消除了用户对脚本是否正在运行的焦虑。进度条可用于向用户指示长时间运行的脚本或操作的进度。幸运的是,使用 Write-Output cmdlet,您可以根据自己的喜好制作进度条。

打开 myoutput.ps1 文件,并将以下代码添加到脚本文件中现有文件的底部。

下面的代码使用 while 循环来迭代多个步骤。在此示例中,为 100 个步骤。循环的每次迭代都会计算已完成的步骤的百分比,并使用 Write-Output 显示进度条。

进度条是使用以下运算符的组合创建的:

  • * - 将字符串重复指定次数
  • $() - 允许表达式的输出包含在字符串中。

然后,脚本暂停 (Start-Sleep) 1 秒以模拟进度,然后再继续下一步。

# Set the total number of steps for the progress bar
$steps = 100

# Initialize the counter for the current step
$currentStep = 0

# Start a loop that will run for the number of steps
while ($currentStep -lt $steps) {
  # Increment the current step counter
  $currentStep++

  # Calculate the percentage of steps completed
  $percentComplete = [int] ($currentStep / $steps * 100)

  # Display a progress bar using Write-Output
  Write-Output "Progress: [$("=" * $percentComplete)$(" " * ($steps-$percentComplete))] $percentComplete% complete"

  # Pause for 1 second to simulate the progress
  Start-Sleep -Seconds 1
}

现在,运行脚本并查看进度条如何工作。

./myoutput.ps1

下面,您可以看到启动屏幕和进度条。

[玩转系统] PowerShell 写入输出:您友好的输出伴侣

结论

在本教程中,您了解了 Write-Output 如何轻松输出对象、数据类型和自定义格式。此外,您还谈到了使用管道运算符将输出发送到其他命令以进行进一步处理。

无论您是编写简单的消息输出还是复杂的自动化任务,Write-Output 都是创建信息更丰富、更专业的 PowerShell 脚本不可或缺的工具。

有了这些新发现的知识,为什么不将输出写入不同的文件类型,例如 .txt.xml 文件?无论意图如何,输出副本在解决系统或应用程序问题时都会派上用场。 Write-OutputOut-File cmdlet 为您提供了您从未意识到自己需要的功能。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯