简体   繁体   English

从Powershell脚本更改MSBuild属性

[英]Changing MSBuild properties from Powershell script

I'm adding the below targets xml to my csproj (via a nuget package) 我将以下目标xml添加到我的csproj中(通过nuget包)

<Project>
  <Target Name="AfterBuild">
    <PropertyGroup>
      <DockerExe Condition=" '$(DockerExe)'=='' ">"C:\Program Files\Docker\Docker\resources\bin\docker.exe"</DockerExe>
      <ImageName Condition=" '$(ImageName)'=='' ">$(MSBuildProjectName)</ImageName>
      <PowershellExe Condition=" '$(PowerShellExe)'=='' ">C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe</PowershellExe>
    </PropertyGroup>
    <Exec Command="$(PowershellExe) -NonInteractive -executionpolicy Unrestricted -command $(MSBuildThisFileDirectory)..\tools\image_name.ps1" />
    <Exec Command="$(DockerExe) build -t $(ImageName) ." />
  </Target>  
</Project>

and image_name.ps1 contains image_name.ps1包含

$name = $(ImageName)
$name = $name.ToLower()
$name = $name.Replace(".", "_")

echo "Name is:"
echo $name

# $(ImageName) = $name

The Powershell script is actually being called, but $name (and $(ImageName) ) is null and I have no idea how to access and update the ImageName property set in the targets file. Powershell脚本实际上是在被调用,但是$name (和$(ImageName) )为null ,我不知道如何访问和更新目标文件中设置的ImageName属性。 I tried $name = $Env:ImageName but the result of that assignment was also null . 我尝试了$name = $Env:ImageName但是赋值的结果也是null

The reason those variables in the powershell script are nul is because powershell knows absolutely nothing about msbuild. powershell脚本中这些变量为nul的原因是因为powershell对msbuild完全一无所知。 And msbuild didn't inform powershell what the values were supposed to be. 而且,msbuild并没有告知Powershell这些值应该是什么。

Anyways, all that string modification is unnecessary anyways, since msbuild can do it for you using property functions: https://docs.microsoft.com/en-us/visualstudio/msbuild/property-functions?view=vs-2019 无论如何,所有字符串修改都是不必要的,因为msbuild可以使用属性函数为您完成此操作: https ://docs.microsoft.com/zh-cn/visualstudio/msbuild/property-functions?view=vs-2019

Thus you don't even need to call a powershell script to modify the string for you. 因此,您甚至不需要调用powershell脚本来为您修改字符串。

Last of all: Jakobii's answer above is spot on for getting the powershell script to work. 最后:Jakobii的上述答案是使Powershell脚本正常工作的地方。 But in the end, you would not be able to get the modified string back out of the powershell script back into msbuild. 但是最后,您将无法将修改后的字符串从Powershell脚本中重新带回msbuild中。

Im not exactly sure what you are try to do. 我不确定自己要做什么。 but could this be what you are looking for? 但这可能是您想要的吗? .ps1 files can have parameters similar to binary files. .ps1文件可以具有与二进制文件相似的参数。

C:\path\to\image_name.ps1 -ImageName 'Some Image Name'

image_name.ps1 image_name.ps1

param(
    $ImageName
)
$name = $ImageName
$name = $name.ToLower()
$name = $name.Replace(".", "_")

write-host "Name is: $name"

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

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