在VS代码段中保留$forPowershell变量



我可以在Powershell的VS代码中以选项卡间距保存我的代码片段,但当我调用代码片段时,它不显示变量的$,从而一直忽略我的变量。它只会粘贴名称并省略$

当您选择代码片段时,如何将VS代码粘贴到$中?

这是我用于"模板"片段的VS代码JSON文件

{
// Place your snippets for powershell here. Each snippet is defined under a snippet name and has a prefix, body and 
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
// same ids are connected.
// Example:
// "Print to console": {
//  "prefix": "log",
//  "body": [
//      "console.log('$1');",
//      "$2"
//  ],
//  "description": "Log output to console"
// }
"Template": {
"prefix": "template",
"body": [
"<#",
".SYNOPSIS",
"t<Overview of script>",
"",
".SYNTAX",
"t<Cmdlet-Name> -Parameter <value>",
"",
".DESCRIPTION",
"t<Brief description of script>",
"",
".PARAMETER <Parameter_Name>",
"t<Brief description of parameter input required. Repeat this attribute if required>",
"",
".INPUTS",
"t<Inputs if any, otherwise state None>",
"",
".OUTPUTS",
"t<Outputs if any, otherwise state None - example: Log file stored in C:file.log>",
"", 
".EXAMPLE",
"t<Example goes here. Repeat this attribute for more than one example>",
"",
".REMARKS",
"tVersion:        1.0",
"#>",
"",
"#---------------------------------------------------------[Variables]------------------------------------------------------------",
"",
"$var1 = <stuff>",
"$var2 = <stuff>",
"",
"#---------------------------------------------------------[Import Modules]--------------------------------------------------------",
"",
"Import-Module <name>",
"",
"#-----------------------------------------------------------[Functions]------------------------------------------------------------",
"",
"Function <FunctionName> {",
"t[CmdletBindinging()]",
"tparam(",
"tt[Parameter()]",
"tt[string]$MyOptionalParameter,",
"",
"tt[Parameter(Mandatory)]",
"tt[int]$MyMandatoryParameter",
"t)",
"",   
"tTry{",
"tt<code goes here>",
"t}",
"", 
"tCatch {",
"ttWrite-Host $Error.Exception",
"tt$Error.Exception | Out-File Out-File $env:TEMPfile.log",
"ttBreak",
"t}",
"",
"tFinally {",
"tt$time = Get-Date",
"ttcompleted at $time | Out-File $env:TEMPfile.log",
"t}",
"}",
"",
"#-----------------------------------------------------------[Execution]------------------------------------------------------------",
"",
"<FunctionName>",
],
"description": "test"
}
}

当我调用这个片段将模板粘贴到一个新的.ps1文件中时,它省略了所有的$。你是怎么把它们留下来的?

在Visual Studio代码段主体中使用\$嵌入文本$

例如,要嵌入PowerShell变量$HOME,请使用\$HOME

注意:从代码段解析器的角度来看,转义需要单个,但由于代码段被定义为JavaScript字符串,这些字符串本身使用作为转义符,因此需要\才能将单个传递给代码段解析器。

请参阅文档。


作为旁白:

意外使用$$在某种程度上是有效的,但它的目的不是逃跑,它会导致不同的行为

前缀为$$的标识符的位置变成了制表符,因为Visual Studio代码对序列的解释如下:

第一个$变为文字[1],但第二个$和后面的标识符被解释为Visual Studio代码变量引用;如果不存在该名称的内置变量,则将其用作占位符文本。


[1]后面跟有有效Visual Studio代码占位符名称或变量引用的任何$都将按字面处理

最新更新