我正在学习Powershell作为Windows管理的一部分,我遇到了一点问题。我需要为各种系统运行 sysinfo 命令,并从输出中选取OS Name
、OS Version
、Total Physical Memory
等字段。我的问题是输出不是powershell对象,所以我不能使用基于属性的处理。我该怎么做才能只拾取这些字段?我尝试使用 findstr,但对于像 Hotfix 这样具有多个值的字段,它只选取第一行。
命令
systeminfo /S <IP Address> /U Administrator /P <Password>
输出:
Host Name: TEST
OS Name: Microsoft Windows Server 2008 R2 Standard
OS Version: 6.1.7601 Service Pack 1 Build 7601
OS Manufacturer: Microsoft Corporation
OS Configuration: Standalone Server
OS Build Type: Multiprocessor Free
systeminfo -?
表示命令支持格式选项。使用 CSV 格式,可以让 PowerShell 直接导入输出:
systeminfo -fo CSV | ConvertFrom-Csv
这将返回一个自定义的 PSObject,其中包含 OS Name
、Host Name
等属性,您可以使用引号访问这些属性(如 Matt 在他的回答中提到的那样(:$csv.'OS Name'
作为参考,以下是systeminfo -?
在我的机器上显示的内容:
SYSTEMINFO [/S system [/U username [/P [password]]]] [/FO format] [/NH]
Description:
This tool displays operating system configuration information for
a local or remote machine, including service pack levels.
Parameter List:
/S system Specifies the remote system to connect to.
/U [domain]user Specifies the user context under which
the command should execute.
/P [password] Specifies the password for the given
user context. Prompts for input if omitted.
/FO format Specifies the format in which the output
is to be displayed.
Valid values: "TABLE", "LIST", "CSV".
/NH Specifies that the "Column Header" should
not be displayed in the output.
Valid only for "TABLE" and "CSV" formats.
/? Displays this help message.
Examples:
SYSTEMINFO
SYSTEMINFO /?
SYSTEMINFO /S system
SYSTEMINFO /S system /U user
SYSTEMINFO /S system /U domainuser /P password /FO TABLE
SYSTEMINFO /S system /FO LIST
SYSTEMINFO /S system /FO CSV /NH
我可以把答案做得更好,但至少一个开始是这样的:
$file = systeminfo
$file | Where-Object{($_ -like "OS*") -or ($_ -like "Host Name:*")}
将系统信息捕获到一个变量(数组(中,该变量(数组(可以通过管道传输到Where-Object中,以解析出您要查找的数据
输出:
Host Name: TE_ST
OS Name: Microsoft Windows 7 Enterprise
OS Version: 6.1.7601 Service Pack 1 Build 7601
OS Manufacturer: Microsoft Corporation
OS Configuration: Standalone Workstation
OS Build Type: Multiprocessor Free
我试图把它变成一个合适的对象来改善我的答案
我正在做另一个答案,试图不失去我第一个答案的简单性。要继续:
$sysInfo= systeminfo
$output = $sysInfo |
Where-Object{($_ -like "OS*") -or ($_ -like "Host Name:*")} |
ForEach-Object{ $_ -replace ":s+"," = "}
ConvertFrom-StringData($output | Out-String)
同样,systeminfo
被捕获到变量$sysInfo
中。以 $output
捕获所需的输出。
这次我使用ForEach对象-replace ":s+"," = "
替换运行每一行。原因是我要将文本转换为哈希表,该哈希表是一系列name = value
。正则表达式替换将冒号和任何后续空格更改为 =
。
$output的类型为 System.Object[]
。但是,在我的示例中,我们需要它是一个字符串,以便它可以放入ConvertFrom-StringData中,这就是为什么我们将$output管道放入Out-String的原因。
话虽如此,你会得到以下内容:
Name Value
---- -----
OS Manufacturer Microsoft Corporation
OS Version 6.1.7601 Service Pack 1 Build 7601
OS Configuration Member Workstation
OS Name Microsoft Windows 7 Professional
Host Name C4093
OS Build Type Multiprocessor Free
您现在可以对Powershell cmd-lets使用它们
$osInfo = ConvertFrom-StringData($output | Out-String)
$osInfo."Os Name"
"Os Name"
需要用引号引起来,因为它包含一个空格。