【问题标题】:Prevent PowerShell Select-String from parsing colon as a drive letter防止 PowerShell Select-String 将冒号解析为驱动器号
【发布时间】:2016-08-30 03:34:40
【问题描述】:

我有一个配置文件,每次打开我的 PowerShell 窗口时都会执行。由于我做了一些 SSH,我需要确保在启动 PowerShell 后立即添加我的内容。但我想避免询问我的 SSH 密码,只要它已经添加到 ssh-agent。此问题的解决方案描述为here,但适用于 Linux shell。

我已将那里描述的解决方案转换为等效的 PowerShell,如下所示:

$ssh_add = "$env:ProgramFiles/Git/usr/bin/ssh-add.exe"
$ssh_keygen = "$env:ProgramFiles/Git/usr/bin/ssh-keygen.exe"
$my_key_path = "$env:USERPROFILE/.ssh/id_rsa"

$my_ssh_key = & $ssh_keygen -lf $my_key_path
$ssh_keys = & $ssh_add -l

if (!(Select-String -Pattern $my_ssh_key -Path $ssh_keys -SimpleMatch -Quiet))
{
    & $ssh_add -t 5h $my_key_path
}

SSH 密钥恰好包含冒号,PowerShell 似乎将其视为驱动器号。这会导致以下错误消息:

Select-String : Cannot find drive. A drive with the name '4096 SHA256' does not exist.

以下形式的 SSH 密钥:

$my_ssh_key = 4096 SHA256:somelongSSHkey some.email@stackoverflow.com (RSA)
$ssh_keys = 4096 SHA256:anotherlongSSHkey /c/Users/MyUser/.ssh/id_rsa (RSA)

如何防止冒号被解析为驱动器号分隔符?

【问题讨论】:

    标签: powershell powershell-5.0


    【解决方案1】:

    -Path 应该是一条路径。您提供给它的值自然会被解释为路径。您可以转义冒号,但这并不能解决您告诉Select-String 在某物不是路径时将其视为路径的问题。

    您现在需要 -InputObject(可以缩短,因为所有 PS 参数都可以)参数,您现在正在使用 -Path。这将匹配文字字符串,而不是将其视为要搜索的文件。您也可以将$ssh_keys 的内容通过管道传递给Select-String,而不是指定任何路径。

    if (!(Select-String -Input $ssh_keys -Pattern $my_ssh_key -SimpleMatch -Quiet))
    ...
    

    有关完整文档,请参阅 https://technet.microsoft.com/library/hh849903.aspx

    【讨论】:

    • 您能否提供使用-InputObject 并将其传送到Select-String 的示例?
    • 添加了示例。请查看文档以获取更多示例,包括管道的使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多