通过-Command无法将脚本块作为参数传递给powershell.exe [英] Can't pass a script block as a parameter to powershell.exe via -Command

查看:236
本文介绍了通过-Command无法将脚本块作为参数传递给powershell.exe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这个

$Global:commandBlock={
Start-Transcript -path $projectFolder\gruntLog.txt;
grunt $argList;
Stop-Transcript
}

$cmdProc=start-process powershell -ArgumentList ('-command `$Global:commandBlock') -WorkingDirectory $fwd -PassThru -NoNewWindow:$NoNewWindow

并继续获取 $ commandBlock:术语'$ Global:commandBlock'不被识别为cmdlet,函数,脚本文件或可操作程序的名称。

我的猜测是与范围有关。但是变数全球化并没有帮助。添加 -args $ commandBlock

My guess was it has to do with scope. But making variable global didn't help. Adding -args $commandBlock like that:

-ArgumentList ('-command `$Global:commandBlock -args "-commandBlock:$commandBlock"') 
-ArgumentList ('-command `$Global:commandBlock -args $commandBlock"') 

没有帮助

我不知道我在阻止,请阅读这个,但不知道如何应用到我的脚本。

And I'm not sure that I escape variables correctly in the block, read this, but not sure how to apply to my script.

推荐答案

有一些我认为保留的东西首先,当您使用单引号'时,您正在指示PowerShell在字面上运行,这意味着它不会扩展变量,而不是你

There's a few things which I think are keeping this from working. First, when you're using single quotes, ' you're instructing PowerShell to operate literally. This means that it won't expand variables. Not what you're looking for.

一个更好的方法是用这样的子表达式来执行。

A better way to do this is to do it with an subexpression like this.

$Global:commandBlock={
'ham' >> C:\temp\test.txt
}

$cmdProc=start-process powershell -ArgumentList ("-command $($Global:commandBlock)") -PassThru -NoNewWindow:$NoNewWindow

这将给您所需的结果。

子表达式非常好。它允许您在字符串中嵌入一个迷你脚本块,然后在父字符串中扩展。

Subexpressions are pretty sweet. It lets you embed a mini-scriptblock within a string, and it's then expanded out in the parent string.

"today's date is $(get-date), on system: $($env:COMPUTERNAME)"




今天的日期是02/14/2017 11:50:49,在系统上:BEHEMOTH

today's date is 02/14/2017 11:50:49, on system: BEHEMOTH

这篇关于通过-Command无法将脚本块作为参数传递给powershell.exe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆