简体   繁体   English

批处理脚本中的多行Powershell函数

[英]Multiline powershell function inside batch script

I want to run .bat -script which calls some powershell function inside it. 我想运行.bat -script,在其中调用一些powershell函数。 Function is not so small, so I want to split it. 功能不是很小,所以我想将其拆分。 But I cannot do it, escape symbols doesn`t help ( ` , ^ ). 但是我做不到,转义符号无济于事(`, ^ )。 Script example: 脚本示例:

set file=%1

set function="$file=$Env:file; ^
              $hash = CertUtil -hashfile $file SHA256 | Select -Index 1"

powershell -command %function%

You can leave the quote at the end of each line like so: 您可以像这样在每行的末尾加上引号:

set file=%1

set function="$file=$Env:file; "^
           "$hash = CertUtil -hashfile $file SHA256 | Select -Index 1; "^
           "example break line further...."

powershell -command %function%

The ^ works as multiline character but it also escapes the first character, so also a quote would be escaped. ^用作多行字符,但也转义第一个字符,因此也转义了引号。

Do not mix batchfile syntax with PowerShell. 不要将批处理文件语法与PowerShell混合使用。 As @Stephan mentioned $function= won't work in batch file. 正如@Stephan提到的那样, $function=在批处理文件中不起作用。 You need to use set function= instead. 您需要使用set function=来代替。 Let's say I want to execute the following: 假设我要执行以下操作:

Get-Process
Get-ChildItem

Then the code should look like this: 然后,代码应如下所示:

set function=Get-Process; ^
Get-ChildItem;

And you start PowerShell with: 然后使用以下命令启动PowerShell:

powershell -noexit -command %function%

-noexit added so that you can verify that the code was successfully executed. -noexit添加,以便您可以验证代码是否已成功执行。

Also keep in mind that what you pass to PowerShell is batch multiline and in PowerShell it's visible as one line so you have to remember about semicolon (which you actually do but I'm leaving this comment here for future readers). 还请记住,传递给PowerShell的是批处理多行,而在PowerShell中它只显示为一行,因此您必须记住分号(您实际上是在做分号,但我在此留给以后的读者注意)。


There's also another option how to pass variable from batch script to PowerShell. 还有另一种选择如何将变量从批处理脚本传递到PowerShell。 You can do it like this: 您可以这样做:

set name=explorer

set function=get-process $args[0]; ^
get-childitem

powershell -noexit  -command "& {%function% }" %name%

Explanation: 说明:

$args[0] represents first argument passed to the scriptblock. $args[0]表示传递给脚本块的第一个参数。 To pass that argument, add %name% after the scriptblock while starting powershell . 要传递该参数,请在启动powershell在脚本块后添加%name% Also, as pointed out in this answer (credits to @Aacini for pointing this out in comments), you have to add & operator and keep your scriptblock inside curly brackets { } . 另外,如该答案中所指出的那样(在注释中指出, @Aacini表示感谢),您必须添加&运算符并将脚本块保留在大括号{ }


Sidenote : to be honest, I'd avoid running scripts like this. 旁注 :老实说,我避免运行这样的脚本。 Much simpler way would be to just save the file as .ps1 and run this in your batch file: 更简单的方法是将文件另存为.ps1并在批处理文件中运行它:

powershell -noexit -file .\script.ps1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM