变量中的 Powershell 搜索字符串(不是文本文件)

Aru*_*run 5 windows powershell

我试图从存储“systeminfo”命令输出但遇到问题的变量“$a”中搜索名为“Hostname”的字符串。我正在使用“系统信息”来收集更大的数据集。

代码:

$a= (get-systeminfo -computername localhost | select-object hostname, OSNAME, osversion, model, type)  
write-output $a 
select-string $a -pattern "hostname"
Run Code Online (Sandbox Code Playgroud)

错误:

Select-String : Cannot find path 'C:\Users\john001c\@{Hostname=PACCPL-FTN1TM1; OSName=Microsoft Windows 7 Enterprise ; OSVersion=6.1.7601 Service Pack 1 Build 7601; Model=Latitude E
4310; Type=x64-based PC}' because it does not exist.

At line:5 char:14
+ select-string <<<<  $a -pattern "hostname"
    + CategoryInfo          : ObjectNotFound: (C:\Users\john...e=x64-based PC}:String) [Select-String], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SelectStringCommand
Run Code Online (Sandbox Code Playgroud)

在变量中搜索字符串的正确方法是什么?

Zor*_*che 4

Select-string有多个参数集。要在对象(而不是文件)内搜索,您的参数将如下所示。-InputObject请注意,针对非文件的内容需要使用该参数,并且它不能用作位置参数,-InputObject必须显式命名该参数。

参数集:对象选择字符串 [-Pattern] -InputObject

所以试试这个吧。

select-string -pattern "hostname" -InputObject $a
Run Code Online (Sandbox Code Playgroud)