powershell - 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"
必须有更好的选择。
解决方案
你使用了错误的心态。不要尝试使用 PowerShell,因为一切都是字符串。那是类 Unix 的想法,它会像用螺丝刀钉钉子一样工作。您需要切换到面向对象的思维方式,因为在 PowerShell 中您 99% 的时间都在处理对象。
通常,您只需为您正在寻找的简单内容执行此操作:
Get-ChildItem Env:PG* | Sort-Object -Property Name
如果Get-ChildItem
支持的 globbing 不起作用,您可能希望使用Where-Object
与-like
globbing 类似的操作符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.
推荐阅读
- java - 在 RecyclerView 中使用 Glide4 从 url 加载图像时图像加载缓慢
- oracle - SQL Developer 无法在旧数据库版本中打开表
- angular - 在Angular参数中注入依赖项的正确方法是什么
- python - 如何在 django 模板标签中执行 split() 函数?
- python - 如何比较csv文件的三列并用python确定丢失的数据?
- php - 如何显示来自带有 id 的 PHP 文件的图像?
- unit-testing - WebTestClient 不发布对象
- ios - ios 版本 13 中的照片库插件崩溃
- jenkins - 在 Jenkins 管道上获取项目的构建大小
- c++ - C++ 关于使用的指针