[英]How to run Powershell script in VS Code using Powershell Integrated Console
我有这个小脚本,它在 PowerShell 中运行良好(在 VS Code 之外):
$a = @{Portfolio = "CALoan"; Folder = "S:\Data\{yymmdd}"; Filename = "LN{yymmdd}.txt"}
$l = @($a)
$l | ForEach-Object -Process {
$p = ($_.Folder + '\' + $_.Filename).Replace("{yymmdd}", "190911")
if (Test-Path $p) {
[pscustomobject] @{Portfolio = $_.Portfolio; Path = $p; CreateTime = (Get-ChildItem $p).CreationTime}
} else {
[pscustomobject] @{Portfolio = $_.Portfolio; Path = $p; CreateTime = "not found"}
}
} | Out-GridView
但是,在 VSCode 编辑器中查看脚本时,如果我只是右键单击并选择运行代码(使用代码运行器扩展),我会收到大量这样的错误:
PS C:\Users\me> $l | ForEach-Object -Process { Missing closing '}' in statement block or type definition. At line:0 char:0 PS C:\Users\me> $p = ($_.Folder + '\' + $_.Filename).Replace("{yymmdd}", "190911") PS C:\Users\me> if (Test-Path $p) { Missing closing '}' in statement block or type definition. At line:0 char:0 PS C:\Users\me> [pscustomobject] @{Portfolio = $_.Portfolio; Path = $p; CreateTime = (Get-ChildItem $p).CreationTime} Portfolio Path CreateTime --------- ---- ---------- \ {2/28/2019 12:41:46 PM, 2/20/2019 12:32:15 PM, 1/24/2019 3:54:50 PM, 3/15/2019 1:46:40 PM...} PS C:\Users\me> } else { At line:1 char:1 + } else { + ~ Unexpected token '}' in expression or statement. At line:1 char:8 + } else { + ~ Missing closing '}' in statement block or type definition. PS C:\Users\me> [pscustomobject] @{Portfolio = $_.Portfolio; Path = $p; CreateTime = "not found"} Portfolio Path CreateTime --------- ---- ---------- \ not found PS C:\Users\me> } At line:1 char:1 + } + ~ Unexpected token '}' in expression or statement. PS C:\Users\me> } | Out-GridView At line:1 char:1 + } | Out-GridView + ~ Unexpected token '}' in expression or statement. At line:1 char:3 + } | Out-GridView + ~ An empty pipe element is not allowed. PS C:\Users\me>
就好像集成终端一次执行一行,而不是将整个脚本发送到 PowerShell。 这样做的正确方法是什么?
顺便说一句,如果我在 VS Code 中启动一个新的 PowerShell 终端,它会按预期工作(也使用 Code Runner)。 那么,PowerShell 集成控制台和 Code Runner 是怎么回事?
我无法谈论 Code Runner 扩展,但您可以通过安装PowerShell 扩展来绕过该问题,这对于在 Visual Studio Code 中编辑和运行 PowerShell 代码非常有用。
它允许您通过以下方式可靠且更快地运行所选代码(因为不涉及中间脚本文件和外部 PowerShell 进程 - 见下文):
Run Selection
。警告:
默认情况下,您通过 PowerShell 扩展运行的代码在同一个PowerShell 会话中执行,因此后续调用可能会受到先前调用的影响; 例如,如果突出显示包含(++$i)
并重复运行它, $i
的值会不断增加。
打开设置Create Temporary Integrated Console
(通过File > Preferences > Settings
或Ctrl+, )可用于更改它,以便每次调用都会创建一个新的临时会话以在.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.