PowerShell脚本与调试实践

108、查询三个 WMI 类中的每一个。为此,将 Get – CimClass 命令的结果通过管道传递给 ForEach – Object 命令。在脚本块内,调用 Get – CimInstance 并传递 cimclassname 属性。

可以使用以下 PowerShell 命令来实现该需求:


Get-CimClass | ForEach-Object { Get-CimInstance -ClassName $_.CimClassName }

此命令会将

Get-CimClass

的结果传递给

ForEach-Object

进行遍历,在遍历过程中调用

Get-CimInstance

并传入每个类的

CimClassName

属性来查询对应的 WMI 类。

109、使用 Get – CimAssociatedInstance cmdlet 并将 $v 提供给 inputobject 参数。


PS C:> Get-CimAssociatedInstance -InputObject $v

110、使用向上箭头键调出上一条命令。将返回的 WMI 对象通过管道传递给 Get – Member cmdlet。将 Get – Member cmdlet 的结果通过管道传递给 Select – Object cmdlet,并使用 -Unique 开关参数来限制返回的信息量。

下面是给定的【文本内容】::

假设上一条命令返回的 WMI 对象存储在某个变量(这里假设为

$wmiObject

)中,命令如下:


PS C:> $wmiObject | Get-Member | Select-Object * -Unique

注:原答案中

select typename -Unique

只选取了

typename

属性,不太符合题目将

Get-Member

结果传递且使用

-Unique

限制信息量的完整意图,修改为

Select-Object * -Unique

表示选取所有属性并去重。

111、使用向上箭头键调出上一个命令,并对其进行修改,使其仅返回Win32_PNPEntity WMI类的实例。

通常在 PowerShell 中,使用向上箭头键调出上一个命令后,要使其仅返回

Win32_PNPEntity

WMI 类的实例,可使用以下命令:


Get-CimInstance -ClassName Win32_PNPEntity

原答案中的


Get-CimAssociatedInstance -InputObject $v -ResultClassName win32_PNPEntity

并不符合仅获取

Win32_PNPEntity

类实例的要求,因为它是用于获取关联实例,且依赖于

$v

这个输入对象,所以原答案错误。

因此这里给出正确答案为:


Get-CimInstance -ClassName Win32_PNPEntity

112、打开Windows PowerShell ISE或其他脚本编辑器。创建一个名为stepbystep.txt的文本文件,内容为:ou=NorthAmerica ou=SouthAmerica ou=Europe ou=Asia ou=Africa。在脚本的第一行,创建一个名为$aryText的变量,用于保存Get – Content cmdlet返回的对象,将stepbystep.txt文件的路径作为 – Path参数。使用foreach语句遍历数组的每个元素。创建变量$strClass、$strOUName、$objADSI,使用Create方法在Active Directory中创建组织单位(OU),使用SetInfo()方法将更改写回Active Directory,关闭代码块,将脚本保存为

StepByStep.ps1并运行。

以下是按照要求编写的脚本:


$aryText = Get-Content -Path "<stepbystep.txt文件的实际路径>"

foreach ($aryElement in $aryText)
{
    $strClass = "organizationalUnit"
    $strOUName = $aryElement
    $objADSI = [ADSI]"LDAP://dc=nwtraders,dc=msft"
    $objOU = $objADSI.Create($strClass, $strOUName)
    $objOU.SetInfo()
}

将上述脚本保存为

<yourname>StepByStep.ps1

并运行。注意要将

<stepbystep.txt文件的实际路径>

替换为

stepbystep.txt

文件的真实路径。

113、打开 Windows PowerShell ISE 或你喜欢的 Windows PowerShell 脚本编辑器。创建一个名为 OneStepFurther.txt 的文本文件,文件内容为:123 Main Street

Box 123

Atlanta

Georgia

123456

US

united states

8401 – 555 – 345 – 0199

All information is confidential and is for official use only。使用 Get – Content cmdlet 打开该文件,并将数组存储在变量 $aryText 中。创建变量 $strClass、$intUsers、$strName、$objADSI,其中 $strClass 的值为 ‘User’,$intUsers 的值为 9,$strName 的值为 ‘cn=tempUser’,$objADSI 的值为 [ADSI]”LDAP://ou=NorthAmerica,dc=NwTraders,dc=msft”。使用 for 循环从 1 到 9 进行计数。通过将前缀 $strName 与计数器连接来创建用户对象,使用 SetInfo() 方法将新的用户对象写入 Active Directory,从文本文件中为每个用户对象写入属性,使用 SetInfo() 方法提交更改,将脚本保存为

OneStepFurtherPt1.ps1 并运行。然后将 OneStepFurtherPt1.ps1 保存为

OneStepFurtherPt2.ps1,从脚本中删除创建用户的相关代码,将 Create 方法更改为 Delete 方法,保存并运行脚本。

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

打开 Windows PowerShell ISE 或其他脚本编辑器。

创建

OneStepFurther.txt

文件,内容如下:


123 Main Street
Box 123
Atlanta
Georgia
123456
US
united states
8401 - 555 - 345 - 0199
All information is confidential and is for official use only

使用以下代码打开文件并将内容存储在

$aryText

中:


$aryText = Get-Content -Path "c:labsch15OneStepFurther.txt"

创建所需变量:


$strClass = "User"
$intUsers = 9
$strName = "cn=tempUser"
$objADSI = [ADSI]"LDAP://ou=NorthAmerica,dc=NwTraders,dc=msft"

使用

for

循环创建用户对象:


for ($i = 1; $i -le $intUsers; $i++) {
    $newName = $strName + $i
    $objUser = $objADSI.Create($strClass, $newName)
    foreach ($line in $aryText) {
        $attribute, $value = $line -split ':', 2
        if ($attribute -and $value) {
            $objUser.Put($attribute.Trim(), $value.Trim())
        }
    }
    $objUser.SetInfo()
}

将脚本保存为

<yourname>OneStepFurtherPt1.ps1

并运行。


OneStepFurtherPt1.ps1

另存为

<yourname>OneStepFurtherPt2.ps1

删除创建用户的相关代码,将

Create

方法改为

Delete

方法:


for ($i = 1; $i -le $intUsers; $i++) {
    $newName = $strName + $i
    $objUser = $objADSI.Delete($strClass, $newName)
    $objUser.SetInfo()
}

保存并运行

<yourname>OneStepFurtherPt2.ps1

脚本。

114、编写脚本,使用Windows PowerShell ISE或其他脚本编辑器,导入Active Directory模块,从nwtraders.com域的TestOU OU中检索用户,检查用户的description属性是否为空或null,若为空则修改用户的description属性并显示修改信息,最后显示修改的用户数量。


Import-Module ActiveDirectory
$users = Get-ADUser -SearchBase "ou=TestOU,dc=nwtraders,dc=com" -filter '*' -property description
$count = 0
ForEach($user in $users) {
    if([string]::IsNullOrEmpty($user.Description)) {
        Write-Host "Modifying $($user.Name)"
        Set-ADUser -Identity $user.DistinguishedName -Description "added via script"
        $count++
    }
}
Write-Host "Modified $count users"

115、在新安装的Windows Server上安装域控制器,需要分配静态IP地址、重命名服务器并安装AD DS管理工具,请简述操作步骤。

以下是对应各步骤的具体操作命令:

手动使用管理员账户登录服务器。

手动打开Windows PowerShell ISE。

在Windows PowerShell ISE中执行命令:

Set-ExecutionPolicy remotesigned -force

在Windows PowerShell ISE中执行命令:

$ipif = (Get-NetAdapter).ifIndex

在Windows PowerShell ISE中执行以下命令设置静态IP地址:

powershell
$ipaddress = "192.168.0.225"
$ipprefix = "24"
$ipgw = "192.168.0.1"
$ipdns = "192.168.0.225"
$ipif = (Get-NetAdapter).ifIndex
New-NetIPAddress -ipaddress $ipaddress -prefixlength $ipprefix -interfaceindex $ipif -defaultgateway $ipgw

在Windows PowerShell ISE中执行命令:

$newname = "dc8508"; Rename-Computer -NewName $newname -force

在Windows PowerShell ISE中执行以下命令添加功能和角色:

powershell
Add-WindowsFeature -Name "ad-domain-services" -IncludeAllSubFeature -IncludeManagementTools
Add-WindowsFeature -Name "dns" -IncludeAllSubFeature -IncludeManagementTools
Add-WindowsFeature -Name "gpmc" -IncludeAllSubFeature -IncludeManagementTools

在Windows PowerShell ISE中执行命令:

Restart-Computer

116、将服务器添加到新林,步骤如下:1. 以管理员身份登录刚重启的服务器。2. 打开Windows PowerShell ISE。3. 创建一个变量用于存储完全限定域名。4. 创建一个变量用于存储NetBIOS名称。5. 导入ADDSDeployment模块。6. 将Install – ADDSForest cmdlet添加到脚本中,设置 – CreateDnsDelegation参数为false。7. 指定 – DatabasePath、 – DomainMode、 – DomainName和 – DomainNetbiosName参数。8. 指定 – ForestMode、 – LogPath和 – SysVolpath参数,以及 – InstallDns和 – NoRebootonCompletion参数的选项,使用 – Force参数。9. 运行脚本,输入目录还原密码两次,配置完成后服务器将重启,使用目录还原密码登录服务器。

以下是对应步骤的具体操作及代码示例:

以管理员身份登录刚重启的服务器。

此步骤为手动操作,通过服务器登录界面,使用管理员账号和密码登录。

打开Windows PowerShell ISE。

此步骤为手动操作,在开始菜单中搜索“Windows PowerShell ISE”并打开。

创建一个变量用于存储完全限定域名。

示例代码:

powershell
$domainname = "nwtraders.msft"

创建一个变量用于存储NetBIOS名称。

示例代码:

powershell
$netbiosName = "NWTRADERS"

导入ADDSDeployment模块。

示例代码:

powershell
Import-Module ADDSDeployment

将Install-ADDSForest cmdlet添加到脚本中,设置 -CreateDnsDelegation 参数为

false



示例代码:

powershell
Install-ADDSForest -CreateDnsDelegation:$false `

指定 -DatabasePath、-DomainMode、-DomainName 和 -DomainNetbiosName 参数。

示例代码:

powershell
-DatabasePath "C:WindowsNTDS" `
-DomainMode "Win2012" `
-DomainName $domainname `
-DomainNetbiosName $netbiosName `

指定 -ForestMode、-LogPath 和 -SysvolPath 参数,以及 -InstallDns 和 -NoRebootOnCompletion 参数的选项,使用 -Force 参数。

示例代码:

powershell
-ForestMode "Win2012" `
-InstallDns:$true `
-LogPath "C:WindowsNTDS" `
-NoRebootOnCompletion:$false `
-SysvolPath "C:WindowsSYSVOL" `
-Force:$true

完整脚本示例如下:

InstallNewForest.ps1


# Create New Forest, add Domain Controller
$domainname = "nwtraders.msft"
$netbiosName = "NWTRADERS"
Import-Module ADDSDeployment
Install-ADDSForest -CreateDnsDelegation:$false `
-DatabasePath "C:WindowsNTDS" `
-DomainMode "Win2012" `
-DomainName $domainname `
-DomainNetbiosName $netbiosName `
-ForestMode "Win2012" `
-InstallDns:$true `
-LogPath "C:WindowsNTDS" `
-NoRebootOnCompletion:$false `
-SysvolPath "C:WindowsSYSVOL" `
-Force:$true

运行脚本,输入目录还原密码两次,配置完成后服务器将重启,使用目录还原密码登录服务器。

此步骤为手动操作,在运行脚本时,按照提示输入目录还原密码两次,等待配置完成服务器重启后,使用该密码登录服务器。

117、打开Windows PowerShell ISE。创建一个名为My – Function的函数,函数内容如下所示。将该函数保存到一个名为my – function.ps1的文件中。选择语句“$a plus $b equals four”所在的代码行。从“调试”菜单中选择“切换断点”。运行My – Function脚本,将函数加载到内存中。在Windows PowerShell ISE的底部窗格(命令窗格)中,输入函数名以执行该函数。在Windows PowerShell ISE的输出窗格中,检查输出并确定断点所在的行。检查Windows PowerShell ISE命令窗格中的提示符。在Windows PowerShell ISE命令窗格的调试提示符下,检查$a变量的值。现在检查$b变量的值。现在将$a和$b都赋值为2。现在,从“调试”菜单中选择“单步跳出”。从“调试”菜单中选择“移除所有断点”。检查脚本窗格。在Windows PowerShell ISE的命令窗格中,再次调用My – Function。修复该函数。将修订后的函数保存为my – function1.ps1。

操作步骤

按照以下步骤操作:

打开Windows PowerShell ISE。

创建函数

My-Function

,其内容为:

powershell
Function my-function {
Param([int]$a, [int]$b)
"$a plus $b equals four"
}


并保存到

my-function.ps1

文件。

选择

"$a plus $b equals four"

这行代码。

从“调试”菜单选“切换断点”。

运行

My-Function

脚本加载函数到内存。

在命令窗格输入

My-Function

执行函数。

在输出窗格确定断点所在行。

查看命令窗格提示符,应前缀

[DBG]

在调试提示符下,输入

"$a"

查看

$a

变量值,输入

"$b"

查看

$b

变量值。

输入

"$a = $b = 2"


$a


$b

赋值

2

从“调试”菜单选“单步跳出”。

从“调试”菜单选“移除所有断点”,脚本窗格高亮行应恢复正常。

在命令窗格再次调用

My-Function

修复函数,将输出行改为:

powershell
"$a plus $b equals $($a + $b)"


保存为

my-function1.ps1

118、打开 Windows PowerShell 控制台。使用 Set – PSBreakPoint 命令在脚本 my – function.ps1 中的 my – function 函数上设置断点。将 my – function 函数引入当前的 Windows PowerShell 会话。使用 Get – PSBreakPoint 命令显示断点。使用 Remove – PSBreakPoint 命令移除 my – function 函数的断点。不指定脚本为 my – function 函数设置断点。调用 my – function 函数。在调试模式下,显示 $a 变量和 $b 变量的值。输入 exit 命令退出调试模式。点源化 my – function1.ps1 脚本。运行 my – function 函数,并为 a 参数提供值 12,为 b 参数提供值 14。查询 $a 和 $b 的值。将 $b 的值更改为 0,然后退出调试模式。使用 Get – PSBreakPoint 命令检索所有断点,并将其通过管道传递给 Remove – PSBreakPoint 命令。使用 Get – PSBreakPoint 命令确保断点已被移除。

以下是完成上述操作的具体步骤及命令:

打开 Windows PowerShell 控制台。

设置断点:

powershell
Set-PSBreakPoint -Script my-function.ps1 -Command my-function

引入函数到当前会话:

powershell
. .my-function.ps1 # 假设脚本在当前目录下,根据实际路径修改
my-function

显示断点:

powershell
Get-PSBreakPoint

移除断点:

powershell
Remove-PSBreakpoint -Id 0 # 假设该断点的 Id 为 0,可通过 Get-PSBreakPoint 查看实际 Id

不指定脚本设置断点:

powershell
Set-PSBreakPoint -Command my-function

调用函数进入调试模式:

powershell
my-function

在调试模式下显示变量值:

powershell
[DBG]: PS C:>> $a
[DBG]: PS C:>> $b

退出调试模式:

powershell
[DBG]: PS C:>> exit

点源化脚本:

powershell
. .my-function1.ps1 # 假设脚本在当前目录下,根据实际路径修改

运行函数并传入参数:

powershell
my-function -a 12 -b 14

查询变量值:在调试模式下执行

$a


$b

查看值。

修改

$b

值并退出调试模式:

powershell
[DBG]: PS C:>> $b = 0
[DBG]: PS C:>> exit

移除所有断点:

powershell
Get-PSBreakPoint | Remove-PSBreakPoint

确保断点移除:

powershell
Get-PSBreakPoint # 若无输出则表示断点已移除

119、打开 Windows PowerShell ISE,创建一个名为 PromptForChoiceExercise.ps1 的新脚本,按要求创建变量 caption、message、choices、defaultChoice,调用 PromptForChoice 方法,创建一个开关语句来评估返回值,保存并运行脚本,然后测试三个选项中的每一个。

打开 Windows PowerShell ISE。

创建一个名为

PromptForChoiceExercise.ps1

的新脚本。

创建用于标题的变量

caption

,并为其赋值字符串

"This is the caption"

powershell
$caption = "This is the caption"

创建用于消息的变量

message

,并为其赋值字符串

"This is the message"

powershell
$message = "This is the message"

创建名为

choices

的变量以保存

ChoiceDescription

对象,创建包含三个选项(choice1、choice2、choice3)的数组:

powershell
$choices = [System.Management.Automation.Host.ChoiceDescription[]] @("&choice1", "c&hoice2", "ch&oice3")

创建整数变量

defaultChoice

并赋值为 2:

powershell
[int]$defaultChoice = 2

调用

PromptForChoice

方法并将返回值赋给

choiceRTN

变量:

powershell
$choiceRTN = $host.ui.PromptForChoice($caption, $message, $choices, $defaultChoice)

创建开关语句来评估

choiceRTN

变量中的返回值:

powershell
switch($choiceRTN) {
0 { "choice1" }
1 { "choice2" }
2 { "choice3" }
}

保存并运行脚本,依次运行脚本三次并选择每个选项以测试三个选项是否正常工作。

© 版权声明

相关文章

暂无评论

none
暂无评论...