在1个任务中设置属性值,并在另一个任务中使用更新的值

时间:2012-01-27 20:35:48

标签: powershell psake

在我的psake构建脚本中,我有一个名为$ build_mode的属性,我设置为“Release”。

我有2个任务; “Compile_Debug”,“Compile_Release”。在Compile_Debug中,我将$ build_mode更改为“Debug”,并且在该任务执行时它可以正常工作;但是,如果我之后有另一个使用$ build_mode的任务执行,$ build_mode将返回“Release”。

有没有办法在Psake构建脚本中全局更改或设置变量,以便可以在任务之间使用更新的值?

(我正在尝试进行1次“测试”或1次“打包”任务,而不是“Test_Debug”等。)

代码:

properties {
    $build_mode = "Release"
}

task default -depends Compile_Debug, Test

task Compile_Debug {
    $build_mode = "Debug"
    # Compilation tasks here that use the Debug value
}

task Test {
        # Test related tasks that depend on $build_mode being updated.
}

2 个答案:

答案 0 :(得分:4)

我通常将构建模式设置为@manojlds建议,在Invoke-Psake调用中作为参数传入。但是,如果您再次发现自己想要修改任务A中对象的值并且可以访问任务B中的修改值,则可以采用以下方法:

在任务B中无法访问$ build_mode的修改值这一事实是由于powershell作用域。当您在任务A中为$ buildMode变量设置值时,该更改在任务A的范围内进行,因此在其外部变量值保持不变。

实现目标的一种方法是使用作用于整个脚本的散列表来存储对象:

<强>代码:

properties {
    #initializes your global hash
    $script:hash = @{}
    $script:hash.build_mode = "Release"
}

task default -depends Compile_Debug, Test

task Compile_Debug {
    $script:hash.build_mode = "Debug"
    # Compilation tasks here that use the Debug value
}

task Test {
        # Test related tasks that depend on $script:hash.build_mode being updated.
}

唯一需要注意的是,每次要引用构建模式时,都必须使用long $ script:hash.build_mode名称,而不仅仅是$ build_mode

答案 1 :(得分:2)

为什么不将构建模式作为参数传递给Invoke-Psake中的任务?

 Invoke-Psake "$PSScriptRoot\Deploy\Deploy.Tasks.ps1" `
        -framework $conventions.framework `
        -taskList $tasks `
        -parameters @{
                "build_mode" = "Debug"
            }

在任务中,您现在可以使用$build_mode

相关问题