【问题标题】:How to add a command line argument to powershell in profile.ps1 for Alias?如何在 profile.ps1 for Alias 中向 powershell 添加命令行参数?
【发布时间】:2023-03-11 06:13:01
【问题描述】:

我对 Powershell 还是很陌生,但我想将我最喜欢的编辑器添加到 Powershell 中的别名中。

我在C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1 中编辑了profile.ps1,它将在PowerShells 启动时自动运行。

我尝试输入 New-Alias np notepad.exe,每次启动 PowerShell 时都能完美运行。


但是,我想使用Sublime Text 3 作为我的编辑器。我按照此 SO 页面中的说明进行操作:How can I write a PowerShell alias with arguments in the middle?

Sublime Text 我需要的命令行是"C:\Program Files\Sublime Text 3\sublime_text.exe" -n [FirstArg]

我出来的是这样的:function sublime { 'C:\Program Files\Sublime Text 3\sublime_text.exe' -n $args }

它不起作用,我收到这样的错误:

At C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1:5 char:72
+ ... lime {  'C:\Program Files\Sublime Text 3\sublime_text.exe' -n $args }
+                                                                ~~
Unexpected token '-n' in expression or statement.
At C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1:5 char:75
+ ... lime {  'C:\Program Files\Sublime Text 3\sublime_text.exe' -n $args }
+                                                                   ~~~~~
Unexpected token '$args' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : UnexpectedToken

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 你错过了调用运算符&
  • @PetSerAl 因为我对 PS 还是很陌生,请给我一个例子好吗?非常感谢。
  • 您是否启动过任何名称中带有空格的程序?如果是,那么做同样的事情。如果没有,然后找到如何做到这一点。互联网上应该有很多关于这方面的信息。
  • @PetSerAl 是的。在 Linux 中,当我想在路径中设置一个带空格的别名时,我可以在其中使用引号,例如:export sublime="/path/to/Sublime Text 3"。这就是为什么我对& 感到困惑。不过还是谢谢。
  • '...' 只是一串字符,它不会运行任何东西。你需要 & 来运行字符串中的东西,例如& 'C:\Program Files\Sublime Text 3\sublime_text.exe' -n $args

标签: powershell sublimetext3 alias


【解决方案1】:

如果不是 Sublime 用户,我怀疑这应该可行:

function Start-Sublime {
    param([string]$args)

    $limeArgs = [string]::Empty
    if ($args -ne $null) {
        $limeArgs = $args
    }

    Start-Process "$env:ProgramFiles\Sublime Text 3\sublime_text.exe" -n $limeArgs
}

Set-Alias lime Start-Sublime

不是最漂亮的 PowerShell 代码,但我想它会满足您的需求。它比神秘的 & 运算符更容易理解。

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多