Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 如果未设置TFS构建变量,如何返回默认值?_Powershell_Tfs - Fatal编程技术网

Powershell 如果未设置TFS构建变量,如何返回默认值?

Powershell 如果未设置TFS构建变量,如何返回默认值?,powershell,tfs,Powershell,Tfs,我想创建一个Powershell脚本,该脚本既可以在生成代理上下文中的TFS上执行,也可以在本地执行。在TFS上,可以使用各种工具,例如$(Build.SourcesDirectory)。同时,该脚本在源代码树中也可用,因此我希望能够在本地运行它,而这些变量没有设置。我发现返回默认值的最短方法是以下Try..Catch块,其中包含令人不安的长异常类型: Try { $SourcesDirectory = $(Build.SourcesDirectory) } Catch [System.

我想创建一个Powershell脚本,该脚本既可以在生成代理上下文中的TFS上执行,也可以在本地执行。在TFS上,可以使用各种工具,例如
$(Build.SourcesDirectory)
。同时,该脚本在源代码树中也可用,因此我希望能够在本地运行它,而这些变量没有设置。我发现返回默认值的最短方法是以下
Try..Catch
块,其中包含令人不安的长异常类型:

Try {
    $SourcesDirectory = $(Build.SourcesDirectory)
}
Catch [System.Management.Automation.CommandNotFoundException] {
    $SourcesDirectory = "..\..\Local\Path\To\Sources\Directory"
}

Write-Output $SourcesDirectory

有没有“更好”的方法来实现这一点?

当然,您可以使用一个简单的内联if语句。我不确定
$(Build.SourcesDirectory)
是否有任何副作用,但使用
$env:Build\u SourcesDirectory
这应该可以:

$sourcesDirectory = if($env:BUILD_SOURCESDIRECTORY) { $env:BUILD_SOURCESDIRECTORY } else { "..\..\Local\Path\To\Sources\Directory" }

可以将变量添加到本地环境变量:

  • 以管理员身份打开CMD
  • 运行此命令:
    setx Build.sources目录“C:\Path”

现在,变量也可在本地计算机中使用,您不需要
尝试/catch
如果/else
,使用变量
$env:BUILD\u sources目录
运行PowerShell脚本,它也将在本地计算机和构建过程中运行


无论如何,您应该使用
$env:BUILD\u SOURCESDIRECTORY
而不是
$(BUILD.SOURCESDIRECTORY)
使其在构建中工作。

这是个好消息!你知道在文档中,
$(Foo.Bar)
$env:Foo\u Bar
的等价物在哪里被记录?我在链接的预定义生成变量文档的上下文中找不到它。您可以在此处看到(向下滚动并选择PowerShell选项卡)