如何将here-string作为参数传递给终端中的powershell脚本?

时间:2019-05-24 19:43:30

标签: powershell herestring

我有一个名为“ file1.ps1”的Powershell脚本,如下所示,该脚本运行良好:

$herestring = @"
State = Defined
FiscalWeek =
"@

$hash = ConvertFrom-StringData $herestring

$hash | Format-Table

此文件提供以下输出:

PS C:\temp> .\file1.ps1

Name                           Value                                                                                                                                     
----                           -----                                                                                                                                     
State                          Defined                                                                                                                                   
FiscalWeek                                                                                                                                                               

现在,我想将$ herestring作为参数传递给此文件。因此,修改后的脚本如下所示:

param ($herestring)

$hash = ConvertFrom-StringData $herestring

$hash | Format-Table

因此,当我在Powershell ISE或vscode的终端中运行此命令时,由于其中包含换行符,因此我无法粘贴或传递$ herestring。

PS C:\Temp> .\file2.ps1 -herestring 

当我尝试粘贴时,每一行都被视为单独的命令。

PS C:\Temp> .\file2.ps1 -herestring @"
The string is missing the terminator: "@.
At line:0 char:0
PS C:\Temp> State = Defined
State : The term 'State' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was 
included, verify that the path is correct and try again.
At line:1 char:1
+ State = Defined
+ ~~~~~
    + CategoryInfo          : ObjectNotFound: (State:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

PS C:\Temp> FiscalWeek =
FiscalWeek : The term 'FiscalWeek' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path 
was included, verify that the path is correct and try again.
At line:1 char:1
+ FiscalWeek =
+ ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (FiscalWeek:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

PS C:\Temp> "@

在这种情况下,如何提供here-string作为参数?

我尝试将here-string构造为单引号以及三个连续的双引号中的单行。另外,尝试使用反引号n和反引号r

要么导致语法错误,要么没有给出预期的结果。

1 个答案:

答案 0 :(得分:0)

我不知道为什么您的Powershell在出现新行时执行,而不是提示您完成命令。这个对我有用。这是PS 5.1。如果它是较旧的版本,则可能会对其进行更新。

enter image description here