我是Powershell的新手,正在尝试完成一项任务



我开始使用Powershell,我一直在网上学习一些课程。此时此刻,我陷入了一个挑战,我希望有好的灵魂可以帮助我从课程的说明。

指令:

1-找出服务器机器上安装了哪些Windows特性。(我正在远程命令到一台名为"服务器"的计算机)

2-只选择Name和InstallState列中存储的数据。

3-根据Name属性按升序(字母顺序)对数据排序。

4-确保输出格式设置为table

5-将最终输出保存到桌面电脑的C:features.txt文件中。

我想到的是:

Invoke-Command -ComputerName Server -ScriptBlock{
>> Get-WindowsFeature | Select-Object -Property Name, InstallState | Sort-Object -Property Name | Format-Table
>> } | Out-File C:features.txt

我尝试过使用和不使用选择对象命令,因为我知道format-table命令在这种情况下几乎是相同的。谢谢你!

当我在远程计算机上调用scriptblock时,我将其赋值给一个变量,然后处理结果如下:

$myResults= Invoke-Command -ComputerName Server -ScriptBlock{…}
Foreach ($item in $myResults){
Write-host” $item.name / 
$item.nstallState”
}

你过度地使用管道,这并没有错,但对我个人来说,我自己还是一个初学者,完全理解他们每个人到底是什么,并转发到下一个是不容易的。不要试图在第一次尝试时就写出一条包含几个要点的完美线条。从任务中最小最快的部分开始。在这种情况下,你只需要把它们都取出来,而不需要过滤器和管道。然后在此基础上继续工作,做一些修改,使用write-host来显示结果,并自己跟踪和错误,以更深入地理解每个结果。最后你可以把它们锁起来。

invoke-command -computername server -scriptblock {Get-WindowsFeature | ? installstate -eq installed | select-object name,installstate | sort-object name | format-table} | out-file c:features.txt

以我的评论为例

# 1-Find out what Windows features are installed on the server machine. 
Get-WindowsFeature
# Results
<#
#>

# 2-Select only the data stored in the Name and InstallState columns.
Get-WindowsFeature | 
Select-Object -Property Name, InstallState
# Results
<#
#>
# 3 - Sort the data by the Name property in ascending (alphabetical) order.
Get-WindowsFeature | 
Select-Object -Property Name, InstallState | 
Sort-Object -Property Name
# Results
<#
#>
# 4-Make sure the output format is set to table
Get-WindowsFeature | 
Select-Object -Property Name, InstallState | 
Sort-Object -Property Name | 
Format-Table # though this is not needed, since table is the default for less than 5 properties.
# Results
<#
#>
<#
# 5-Save the final output into a file called C:features.txt on your desktop 
machine.
#>
Get-WindowsFeature | 
Select-Object -Property Name, InstallState | 
Sort-Object -Property Name | 
Export-Csv -Path 'SomePathName' -NoTypeInformation -Append

# (I'm remoting command to a computer named "Server")
$Computers | 
ForEach-Object {
Invoke-Command -ComputerName $PSItem.ComputerName -ScriptBlock{
Get-WindowsFeature | 
Select-Object -Property Name, InstallState | 
Sort-Object -Property Name | 
Export-Csv -Path 'SomePathName' -NoTypeInformation  -Append
} 
}

最新更新