如何存储变量并将其用作 Get-Content 的 -Pattern?

huangapple go评论56阅读模式
英文:

How to store variable and use it as a -Pattern from Get-Content?

问题

The first code you provided works fine, but when you try to use the variables from a text file, it's not working. To use the content of the text file as a -Pattern in Select-String, you should modify your code like this:

$Pattern = Get-Content C:\temp\list.txt | ForEach-Object { $_.Trim('"') }
$software = Get-Package | Select-Object -ExpandProperty Name
$array = $software | Out-File C:\temp\installed.txt
$SEL = Select-String -Path C:\temp\installed.txt -Pattern $Pattern
if ($SEL) { Write-Host "Found => $($SEL.Line)" } else { Write-Host "Nothing Found" }

This code will read the patterns from the text file, remove the double quotes, and then use them as the -Pattern in Select-String.

英文:

Trying to check if few software are installed, when I use this code, it works fine:

$Pattern = "Winr","adobe";$software = get-package | Select-Object Name; $array = @($software.name) | Set-Content C:\temp\installed.txt; $SEL = Select-String -Path C:\temp\installed.txt -Pattern $Pattern; if ($SEL -ne $null) {write-host Found => $SEL.Line} else {write-host Nothing Found}

This code works without issues, but when I try to get the variables from a text file, it is not working with this code:

$Pattern = Get-Content C:\temp\list.txt; $software = get-package | Select-Object Name; $array = @($software.name) | Set-Content C:\temp\installed.txt; $SEL = Select-String -Path C:\temp\installed.txt -Pattern $Pattern; if ($SEL -ne $null) {write-host Found => $SEL.Line} else {write-host Nothing Found}

如何存储变量并将其用作 Get-Content 的 -Pattern?

The text file contain the following text:

"Winr","adobe"

How to use the content of the text file as a -Pattern in Select-String

Any idea to solve this issue?
Regards

答案1

得分: 2

list.txt应该如下所示:

winr
adobe

为了让$pattern成为一个字符串数组,你可以使用以下代码:

$pattern = get-content list.txt
select-string -pattern $pattern -path installed.txt

请注意,你也可以简单地使用以下方式:

get-package *winr*,*adobe*

或者

$pattern = echo *winr*,
  *adobe*
get-package $pattern

由于get-package接受名称的字符串数组,并且可以使用通配符。 (仅适用于msi和programs提供程序的PowerShell 5.1版本。)

英文:

list.txt should look like:

winr
adobe

for pattern to be an array of strings:

$pattern = get-content list.txt
select-string -pattern $pattern -path installed.txt

Note that you can simply say:

get-package *winr*,*adobe*

or

$pattern = echo *winr*,
  *adobe*
get-package $pattern

Since get-package accepts a string array of names and you can use wildcards. (Powershell 5.1 only for msi and programs providers.)

huangapple
  • 本文由 发表于 2023年5月7日 22:00:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194377.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定