如何在Visual Studio Code中运行PowerShell脚本?

3
我有几个 Powershell 脚本(简单的)想要在 Visual Studio Code 中执行。当我按 F5 运行时,VSC 会变成橙色(调试模式)几秒钟,然后又恢复正常而没有显示任何内容。
这是控制台输出:
PS C:\Users\Huberdo\Documents\WindowsPowerShell> c:\Users\Huberdo\Documents\Meine Projekte\HD-Powershell-Scripts\Mailbox\HD-Mailbox.ps1 PS C:\Users\Huberdo\Documents\Meine Projekte\HD-Powershell-Scripts\Mailbox> 脚本应该使用 `Write-Host` 让我进行选择,但它没有。以下是主要脚本:
function Show-Menu() {

Write-Host "================ $Title ================"

Write-Host "1: Press '1' for this option."
Write-Host "2: Press '2' for this option."
Write-Host "3: Press '3' for this option."
Write-Host "Q: Press 'Q' to quit."


do {
    Show-Menu
    $input = Read-Host "Please make a selection"
    switch ($input) {
        '1' {
            cls
            'You chose option #1'
        } '2' {
            cls
            'You chose option #2'
        } '3' {
            cls
            'You chose option #3'
        } 'q' {
            return
        }
    }
    pause
}
    until ($input -eq 'q')
}

我已经安装并激活了Powershell扩展。我在谷歌和Stackoverflow上搜索了可能的解决方案或类似的问题,但是没有找到任何答案。

我做错了什么吗?我尝试了x86和x64 PS。

1个回答

1
您在 Show-Menu 函数中缺少一个闭合括号。
function Show-Menu() {

Write-Host "================ $Title ================"

Write-Host "1: Press '1' for this option."
Write-Host "2: Press '2' for this option."
Write-Host "3: Press '3' for this option."
Write-Host "Q: Press 'Q' to quit."
}

do {
    Show-Menu
    $input = Read-Host "Please make a selection"
    switch ($input) {
        '1' {
            cls
            'You chose option #1'
        } '2' {
            cls
            'You chose option #2'
        } '3' {
            cls
            'You chose option #3'
        } 'q' {
            return
        }
    }
    pause
}
    until ($input -eq 'q')

如果这不能解决你的问题 - 那么我建议你检查一下是否正确安装了PowerShell扩展,并在VS中创建PowerShell脚本时选择:

文件 -> 新建项目 -> PowerShell -> PowerShell脚本项目

这是因为代码只是在 Show-Menu 函数中调用 ShowMenu,当你调用 Show-Menu 时它无法停止循环。 - JPBlanc
嗨,感谢您的回答。我已经采纳了您的建议,并在预装的 ISE 中尝试了相同的操作,一切都正常。但是,在 Visual Studio Code 中无法正常工作。此外,我没有“文件->新建项目”菜单。我使用的是 Visual Studio Code 而不是 Visual Studio。 - GeraltDieSocke
1
@GeraltDieSocke 哦,好的。抱歉没注意到你用的是Visual Studio Code。所以我不能证明它,因为我用的是Visual Studio 2013。嗯,我会尝试上面发布的代码。我可以从Visual Studio运行它,并提示输入值。在你原来的代码中,你把所有东西都包装在函数中,所以函数从未被调用。这就是为什么脚本可能会运行并退出的原因。 - Christopher
@GeraltDieSocke 嗯,你尝试在VSCode菜单中重新加载Powershell扩展了吗?(这里有第二张截图:http://mikefrobbins.com/2017/08/24/how-to-install-visual-studio-code-and-configure-it-as-a-replacement-for-the-powershell-ise/) - Christopher
1
@GeraltDieSocke,一旦我进行了更正,我在Visual Studio Code(1.19.3)中运行代码,它可以正常工作(PowerShell语言支持1.5.1)。 - JPBlanc
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接