首页 > 解决方案 > powershell中的grep gci输出

问题描述

我正在尝试确定是否设置了一些环境变量(对于 postgres 环境)。他们通常以PG开头。(例如 PGUSER、PGPASSWORD 等)。以下命令会输出它。(前提是我之前设置过)。

gci env:* | sort name | more

为了消除滚动,我尝试了以下方法:

gci env:* | sort name | select-string "PG"

这不会返回任何东西。我在这里做错了什么?

编辑:我现在的替代方案:

gci env:* | sort name  | % { $var = $_.Name + ":" + $_.Value; Write-Output $var } | select-string "PG"

必须有更好的选择。

标签: powershellgrep

解决方案


你使用了错误的心态。不要尝试使用 PowerShell,因为一切都是字符串。那是类 Unix 的想法,它会像用螺丝刀钉钉子一样工作。您需要切换到面向对象的思维方式,因为在 PowerShell 中您 99% 的时间都在处理对象。

通常,您只需为您正在寻找的简单内容执行此操作:

Get-ChildItem Env:PG* | Sort-Object -Property Name

如果Get-ChildItem支持的 globbing 不起作用,您可能希望使用Where-Object-likeglobbing 类似的操作符Get-ChildItem可以做什么:

Get-ChildItem Env:* | Where-Object Name -like 'PG*' | Sort-Object -Property Name

如果你需要搜索值,你可以这样做:

Get-ChildItem Env:* | Where-Object Value -like 'PG*' | Sort-Object -Property Name

如果你想两者都做,你会使用完整的语法Where-Object

Get-ChildItem Env:* | Where-Object { $_.Name -like 'PG*' -or $_.Value -like 'PG*' } | Sort-Object -Property Name

或者您可以使用-match运算符,它可以让您指定一个 .Net 正则表达式:

Get-ChildItem Env:* | Where-Object Name -match '^PG' | Sort-Object -Property Name

Or if you know exactly what you're looking for:

$Vars = 'PGUSER', 'PGPASSWORD'

Get-ChildItem Env:* | Where-Object Name -in $Vars | Sort-Object -Property Name

Remembering, of course, that PowerShell is usually case-insensitive. You can specify -clike, -cmatch, -cin, etc. if you want case-sensitive operators.

Alternately, you can use the $env: automatic variable namespace.

if ($null -eq $env:PGUSER) { 'Not set' }

See also Get-Help about_Environment_Variables.

Beware that setting environment variables permanently is not exactly self-evident. It's described briefly in the above link, but the bottom line is that you have to call [System.Environment]::SetEnvironmentVariable(), which you can find documented here. In Windows land, environment variables are basically legacy features with the exception of Windows OS level variables (like PATH) so they're no longer supported like you might expect.


推荐阅读