2013-04-02 70 views
2

可变我有一个shell脚本应该在后台启动一个.exe文件:解释在PowerShell中{}脚本块

$strPath = get-location 
$block = {& $strPath"\storage\bin\storage.exe" $args} 
start-job -scriptblock $block -argumentlist "-f", $strPath"\storage\conf\storage.conf" 

在前面的Question我发现我需要绝对路径。然而,$ strPath的变量没有解释,如果你看一下下面的命令:

PS Q:\mles\etl-i_test> .\iprog.ps1 --start1 
Start Storage 

Id    Name   State  HasMoreData  Location    Command 
--    ----   -----  -----------  --------    ------- 
37    Job37   Running True   localhost   & $strPath"\storage\bi... 

我怎样才能解决这个问题?

编辑:我知道我需要通过路径作为参数,以及如何?例如:

$block = {& $args[0]"\storage\bin\storage.exe" $args[1] $args[2]} 
start-job -scriptblock $block -argumentlist $strPath, "-f", $strPath"\storage\conf\storage.conf" 

+0

在$ block中变量$ strPath是空的,因为scriptblock是一个全新的脚本。你的脚本块需要接受参数。噢,[不要使用匈牙利语](http://windowsitpro.com/blog/what-do-not-do-powershell-part-5)。不是一个大问题,但实践使得完美。 –

回答

4

脚本块的内容将在另一个无法访问变量的PowerShell.exe实例中执行(作为作业)。这就是为什么您需要将它们发送到Start-Job参数列表中。发送作业所需的所有数据作为参数。例如storage.exe的完整路径,例如

$path = (Get-Location).Path 
$block = {& $args[0] $args[1] $args[2]} 

start-job -scriptblock $block -argumentlist ` 
    "$path\storage\bin\storage.exe" ` 
    "-f", ` 
    "$path\storage\conf\storage.conf" 
+0

我使用这个http://blogs.technet.com/b/heyscriptingguy/archive/2013/05/22/variable-substitution-in-a-powershell-script-block.aspx,但我更喜欢你的解决方案。谢谢。 –

+0

你在答案中缺少一列吗? –