PowerShell脚本编写与高级函数应用

内容分享8小时前发布
1 0 0

table {
border-collapse: collapse;
width: 100%;
margin-bottom: 1rem;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
pre {
background-color: #f8f8f8;
padding: 15px;
border-radius: 4px;
overflow-x: auto;
}

44、修改

CreateMultipleFolders.ps1脚本以删除C:Mytest目录中的10个文件夹,步骤如下:1. 在Windows PowerShell ISE中打开

CreateMultipleFolders.ps1脚本。2. 将If…Else语句中的New – Item cmdlet改为Remove – Item cmdlet。3. 移除Remove – Item cmdlet中的 – name参数,用反斜杠替换。4. 移除Remove – Item cmdlet中的 – type参数。5. 将脚本保存为

DeleteMultipleFolders.ps1并运行。

按照以下步骤修改

<yourname>CreateMultipleFolders.ps1

脚本以删除

C:Mytest

目录中的10个文件夹:

在Windows PowerShell ISE中打开

<yourname>CreateMultipleFolders.ps1

脚本。


If...Else

语句中的

New-Item

cmdlet改为

Remove-Item

cmdlet,修改后脚本块为:

powershell
{
$intPad = 0;
Remove-Item -path c:mytest -name $strPrefix$intPad$i -type directory
}
else
{
Remove-Item -path c:mytest -name $strPrefix$i -type directory
}

移除

Remove-Item

cmdlet中的

-name

参数,用反斜杠替换,修改后脚本块为:

powershell
{
$intPad = 0;
Remove-Item -path c:mytest$strPrefix$intPad$i -type directory
}
else
{
Remove-Item -path c:mytest$strPrefix$i -type directory
}

移除

Remove-Item

cmdlet中的

-type

参数,修改后脚本块为:

powershell
{
$intPad = 0;
Remove-Item -path c:mytest$strPrefix$intPad$i
}
else
{
Remove-Item -path c:mytest$strPrefix$i
}

将脚本保存为

<yourname>DeleteMultipleFolders.ps1

并运行。

45、启动 Windows PowerShell ISE。使用 Get-Verb cmdlet 获取已批准的动词列表。选择一个适合用于按最后修改日期获取文件列表的函数的动词。创建一个名为 Get-FilesByDate 的新函数。为该函数添加四个命令行参数。第一个参数是文件类型数组,第二个参数是月份,第三个参数是年份,最后一个参数是文件路径数组。在函数的 Param 部分之后,添加代码以对通过 $path 变量提供的路径进行递归搜索。将搜索范围限制为仅包含通过 $filetypes 变量提供的文件类型。添加一个 Where-Object 子句,将返回的文件限制为 lastwritetime 属性的月份等于通过命令行提供的月份,且年份等于通过命令行提供的年份。将该函数保存到一个名为 Get-FilesByDate.ps1 的 .ps1 文件中。在 Windows PowerShell ISE 中运行包含该函数的脚本。在命令窗格中调用该函数并为其提供适当的参数。

以下是完成上述任务的详细步骤:

启动 Windows PowerShell ISE。

使用

Get-Verb

cmdlet 获取已批准的动词列表:

powershell
Get-Verb

从列表中选择“Get”作为适合按最后修改日期获取文件列表的动词。

创建名为

Get-FilesByDate

的新函数,并添加四个命令行参数:

powershell
Function Get-FilesByDate {
Param(
[string[]]$fileTypes,
[int]$month,
[int]$year,
[string[]]$path
)
Get-ChildItem -Path $path -Include $fileTypes -Recurse | Where-Object {
$_.LastWriteTime.Month -eq $month -and $_.LastWriteTime.Year -eq $year
}
} # end function Get-FilesByDate

将函数保存到名为

Get-FilesByDate.ps1


.ps1

文件中。

在 Windows PowerShell ISE 中运行包含该函数的脚本。

在命令窗格中调用该函数并提供适当的参数,例如:

powershell
Get-FilesByDate -fileTypes *.docx -month 5 -year 2012 -path c:data

46、启动 Windows PowerShell ISE。打开之前练习中创建的 Get – FilesByDate.ps1 脚本,并使用 Windows PowerShell ISE 的“另存为”功能将文件另存为 Get – FilesByDateV2.ps1。为 $filetypes 输入变量创建一个默认文件类型数组,并将该数组赋值给 $filetypes 输入变量,创建数组时使用数组表示法。使用 [Parameter(Mandatory=$true)] 参数标签使 $month 参数成为必需参数,对 $year 和 $path 参数也执行相同操作。保存并运行该函数。在不指定路径值的情况下调用该函数。现在运行该函数并指定路径值。现在运行该函数并查找不同的文件类型。

启动 Windows PowerShell ISE。

打开

Get-FilesByDate.ps1

脚本,使用“另存为”功能将其保存为

Get-FilesByDateV2.ps1

创建默认文件类型数组并赋值给

$filetypes

变量,示例命令:

powershell
[string[]]$fileTypes = @("*.doc","*.docx")

使

$month


$year


$path

参数成为必需参数,示例代码:

powershell
[Parameter(Mandatory=$true)][int]$month,
[Parameter(Mandatory=$true)][int]$year,
[Parameter(Mandatory=$true)][string[]]$path

保存并运行函数。

不指定路径值调用函数,示例命令:

powershell
Get-FilesByDate -month 10 -year 2011

指定路径值运行函数,示例命令:

powershell
Get-FilesByDate -month 10 -year 2011 -path c:data

查找不同文件类型,示例命令:

powershell
Get-FilesByDate -month 10 -year 2011 -path c:data -fileTypes *.xlsx,*.xls

47、使用Get-Help获取有关导入函数的信息。

可以使用

Get-Help

后接函数名的方式来获取该函数的相关信息。

例如,若要获取

Get-ComputerInfo

函数的信息,可输入:


Get-Help Get-ComputerInfo

它会显示函数的名称、概要、语法、描述、相关链接和备注等内容。

若要查看示例,可输入:


Get-Help Get-ComputerInfo -examples

若要获取更详细信息,可输入:


Get-Help Get-ComputerInfo -detailed

若要获取技术信息,可输入:


Get-Help Get-ComputerInfo -full

48、Use the functions like you would use any other cmdlet.

像使用其他任何 cmdlet 一样使用这些函数。

49、启动 Windows PowerShell ISE。

在不同系统上启动 Windows PowerShell ISE 有不同方法:

在 Windows Server 2012 的开始页面,可输入

PowerShell


Windows PowerShell


Windows PowerShell ISE

会作为搜索结果出现;

在 Windows 8 系统,必须输入

PowerShell_ISE

才能找到

Windows PowerShell ISE

也可以右键单击

Windows PowerShell

图标,从出现的任务菜单中选择

Windows PowerShell ISE

或 “以管理员身份运行 ISE” 来启动;

此外,在 Windows PowerShell 控制台内,只需输入

ise

即可启动。

50、使用 Windows PowerShell ISE 中的 cmdlet(高级函数)代码段为高级函数创建基本框架。

首先启动 Windows PowerShell ISE,然后使用其中的

cmdlet

(高级函数)代码段来创建高级函数的基本框架。

51、将基于注释的帮助从函数体外部移动到函数体内部。


# function Verb - Noun

<#
.Synopsis
简短描述

.DESCRIPTION
详细描述

.EXAMPLE
使用此 cmdlet 的示例

.EXAMPLE
使用此 cmdlet 的另一个示例
#>

52、添加 #requires 语句并要求 Windows PowerShell 版本为 3.0。

在脚本的开头添加语句:#requires -Version 3.0 。

53、将参数名称修改为 computername。添加一个别名属性,其值为 cn。配置 ValueFromPipeline 和 ParameterSetName 的参数属性。将 computername 参数限制为字符串类型。


Param (
    # name of remote computer
    [Alias("cn")]
    [Parameter(ValueFromPipeline=$true, ParameterSetName="remote")]
    [string] $ComputerName
)

54、添加一个 Switch 语句来计算 $PSCmdlet.ParameterSetName。如果 ParameterSetName 等于“remote”,使用 Get – CimInstance 命令的 -ClassName 和 -ComputerName 参数。默认情况下,在不使用 -ComputerName 参数的情况下查询 Get – CimInstance 命令。


Switch ($PSCmdlet.ParameterSetName) { 
    'remote' { 
        Get-CimInstance -ClassName Win32_BIOS -ComputerName $ComputerName 
    } 
    default { 
        Get-CimInstance -ClassName Win32_BIOS 
    } 
} #end switch

55、在Windows PowerShell ISE中运行函数的操作方法是什么?

可按F5键运行整个脚本;若要运行脚本的特定部分,可选中该部分并按F8键运行。

56、在命令面板中,不带参数调用 Get – MyBios 函数。

你应该会收到本地计算机的 BIOS 信息。

57、现在使用 -cn 别名和远程计算机的名称调用 Get – MyBios 函数。

你应该会收到来自远程计算机的 BIOS 信息,示例命令如:


Get-MyBios -cn remoteComputer

其中

remoteComputer

为远程计算机名称。

58、使用帮助并查看高级函数 Get-MyBios 的完整帮助信息。

help Get-MyBios -full

59、打开你在上一个练习中创建的 Get – MyBios.ps1 文件,并将其内容复制到一个空的 Windows PowerShell ISE 脚本窗格中。

打开你在上一个练习中创建的

Get-MyBios.ps1

文件,并将其内容复制到一个空的 Windows PowerShell ISE 脚本窗格中。

60、通过指定.psm1文件扩展名,将新复制的代码保存为一个模块。将你的文件命名为mybios.psm1。从文件菜单中选择“另存为”选项,并将文件保存到一个方便的位置。

在Windows PowerShell ISE中,把复制到空脚本窗格的代码:

从文件菜单选择“另存为”

指定文件扩展名为

.psm1

文件名设为

mybios.psm1

选择合适位置保存

61、在你的 mybios.psm1 文件中,在 Get – MyBios 函数的脚本块结束后,使用 New – Alias cmdlet 创建一个名为 gmb 的新别名。将此别名的值设置为 Get – MyBios。


mybios.psm1

文件里,于

Get-MyBios

函数脚本块结束的位置之后,添加命令:


New-Alias -Name gmb -Value Get-MyBios

来创建别名。

62、将 Export – ModuleMember cmdlet 添加到脚本中,以从 mybios 模块导出所有别名和函数。

在脚本中添加如下命令:


Export-ModuleMember -Function * -Alias *

63、使用 Copy – Modules 脚本在当前用户的目录中创建一个名为 mybios 的模块文件夹,并将模块复制到该位置,请写出具体的操作步骤。

由于不清楚

Copy-Modules

脚本的具体调用方式和环境,以下是通用的思路步骤示例(假设在类 Unix 系统中):

打开终端。

运行

Copy-Modules

脚本,可能的命令格式如下(具体根据脚本实际情况):

bash
./Copy-Modules mybios $HOME/mybios

这里假设脚本接收两个参数,第一个是模块名称,第二个是目标路径。

如果是在 Windows 系统中,可能要在命令提示符或 PowerShell 中运行脚本,命令格式和调用方式会有所不同。实际操作时要根据

Copy-Modules

脚本的具体要求来执行。

64、打开 Windows PowerShell 控制台并使用 Import – Module cmdlet 导入 mybios 模块。

打开 Windows PowerShell 控制台后,在控制台中输入命令:


Import-Module mybios

即可导入

mybios

模块。

65、使用Get – MyBios高级函数返回当前计算机的BIOS信息。

在命令面板中,不带任何参数调用

Get-MyBios

函数,即执行

Get-MyBios

命令,便可获取本地计算机的 BIOS 信息。

66、使用帮助函数从高级函数中检索完整的帮助信息。

help Get-MyBios -full

67、使用Commands附加组件探索与WMI相关的cmdlet,具体步骤如下:1. 启动Windows PowerShell ISE。2. 使用Commands附加组件搜索与WMI相关的cmdlet。3. 从列表中选择Invoke – WmiMethod cmdlet。4. 在类块中,添加WMI类名Win32_Process。5. 在名称块中,输入方法名create。6. 在参数列表中,输入notepad。7. 点击运行按钮。8. 修改ArgumentList块,通过在参数列表中添加calc,使用分号分隔参数。9. 再次点击运行按钮以执行修订后的命令。10. 在Commands附加组件中,查找名称中包含process的cmdlet。从cmdlet列表中选择Stop – Process cmdlet。11. 在Stop – Process块的参数中选择名称参数集。12. 在名称框中,输入notepad和calc。13. 点击运行按钮以执行命令。14. 在显示与进程相关的cmdlet的名称块下,选择Get – Process cmdlet。15. 在名称参数集中,输入calc, notepad。16. 点击运行按钮以执行命令。

启动Windows PowerShell ISE。

利用Commands附加组件搜索与WMI相关的cmdlet。

从搜索结果列表里选择

Invoke-WmiMethod

cmdlet。

在类块处添加WMI类名

Win32_Process

在名称块输入方法名

Create

在参数列表输入

notepad

点击运行按钮。


ArgumentList

块进行修改,在参数列表添加

calc

,用分号分隔参数。

再次点击运行按钮执行修订后的命令。

在Commands附加组件中查找名称含

process

的cmdlet,选择

Stop-Process

cmdlet。


Stop-Process

块的参数中选择名称参数集。

在名称框输入

notepad


calc

点击运行按钮执行命令。

在显示与进程相关cmdlet的名称块下选择

Get-Process

cmdlet。

在名称参数集中输入

calc

,

notepad

点击运行按钮执行命令。

68、使用Windows PowerShell ISE代码片段简化脚本创建,具体步骤如下:1. 启动Windows PowerShell ISE。2. 关闭Commands附加组件。3. 显示脚本窗格。4. 使用Get – WmiObject cmdlet从本地主机检索进程对象列表。将返回的进程对象存储在名为$process的变量中。5. 使用foreach代码片段遍历存储在$process变量中的进程对象集合。6. 将foreach代码片段中的$collection变量更改为$process。7. 在foreach代码片段的脚本块内,使用$item变量显示每个进程对象的名称。8. 点击工具栏上的绿色三角形或按F5运行代码。

以下是按照步骤操作的详细说明:

启动 Windows PowerShell ISE。

关闭 Commands 附加组件。

显示脚本窗格。

在脚本窗格中输入命令:

powershell
$process = Get-WmiObject -Class win32_process

输入时可利用 IntelliSense,如输入

Get-Wm

后按 Enter 选择

Get-WmiObject

cmdlet,输入

-c

后按 Enter 选择

-class

参数。

按 Ctrl + J 启动代码片段,待片段列表出现后,输入

f

快速移至 “F” 部分,可继续输入

fore

后按 Enter 添加

foreach

代码片段,也可在 “F” 部分使用向下箭头选择。代码片段如下:

powershell
foreach ($item in $collection)
{
}

使用鼠标双击代码第 1 行的

$process

变量(仅选中变量名的名词部分,不选美元符号),按 Ctrl + C 复制,再双击

$collection

,按 Ctrl + V 粘贴,修改后的代码如下:

powershell
foreach ($item in $process)
{
}


foreach

代码片段的脚本块内输入

$item.name

点击工具栏上的绿色三角形或按 F5 运行代码,输出应列出系统中每个进程的名称。

完整代码如下:


$process = Get-WmiObject -Class win32_process

foreach ($item in $process) 
{
    $item.name
}

69、在创建基本Windows PowerShell配置文件的过程中,概括其操作步骤。

启动 Windows PowerShell 控制台。

使用

Test-Path $PROFILE

确定配置文件是否存在。

若配置文件存在,使用

Copy-Item $profile c:fsoprofileBackUp.ps1

创建备份。

使用

Remove-Item $PROFILE

删除现有配置文件。

使用

Test-Path $PROFILE

确保文件已删除。

使用

New-Item $PROFILE -ItemType file -Force

创建新配置文件。

使用

ise $profile

在 Windows PowerShell ISE 中打开配置文件。

创建名为

Set-Profile

的函数用于在 ISE 中打开配置文件编辑。


Set-Profile

函数添加

ise $profile

代码。

使用

Save

保存修改并关闭 Windows PowerShell ISE。

关闭 Windows PowerShell 控制台。

打开控制台查找错误。

输入

Set-Profile

测试该函数。

70、描述在添加配置文件功能时,从启动控制台到测试新功能的一系列操作步骤,并按先后顺序总结。

启动 Windows PowerShell 控制台。

调用

Set-Profile

函数(命令:

Set-Profile

)。

在配置文件顶部添加四个部分注释(

#Variables

#Aliases

#PS drives

#Functions

)。

创建三个新变量(

MyDocuments


ConsoleProfile


ISEProfile

)并赋值。

创建两个新别名(

gh

引用

Get-Help


i

引用

Invoke-History

)。

创建两个新 PS 驱动器(

HKCR

引用注册表

HKEY_CLASSES_ROOT


mycerts

引用当前用户

my

位置)。


Set-Profile

函数后添加命令注释(

#commands

)。

添加三个命令(启动转录、设置工作位置到 C 盘根目录、清除控制台)。

保存配置文件,关闭 ISE 和控制台,重新打开控制台查错,测试新功能(命令:

gh


$MyDocuments


$ConsoleProfile


$ISEProfile


sl hkcr:


sl mycerts:


sl c:


Stop-Transcript


set-profile

)。

© 版权声明

相关文章

暂无评论

none
暂无评论...