英文:
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}
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.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论