Skip to content

Instantly share code, notes, and snippets.

@SeeminglyScience
Created January 27, 2020 17:15
Show Gist options
  • Save SeeminglyScience/0989025dd365404a3a9809a33390abef to your computer and use it in GitHub Desktop.
Save SeeminglyScience/0989025dd365404a3a9809a33390abef to your computer and use it in GitHub Desktop.
Example for getting evaluated properties from a csproj. Wrote for a build script I ended up not needing currently.
$FailOnError = @{ ErrorAction = 'Stop' }
$ModuleName = 'MyModule'
$SourcePath = "$PSScriptRoot\src\$ModuleName"
$TargetSdkVersion = '3.1.100'
$FrameworksToProcess = [string[]]::new(0)
$BoundParameters = @{}
$FrameworkPaths = @{}
$AssemblyVersion = ''
$PackageVersion = ''
$dotnet = Get-Command dotnet.exe -CommandType Application -ErrorAction Stop
$sdkFolderBase = Join-Path ($dotnet.Source | Split-Path) -ChildPath sdk
$sdkFolder = Join-Path $sdkFolderBase -ChildPath $TargetSdkVersion
$msbuildLib = Join-Path $sdkFolderBase -ChildPath Microsoft.Build.dll
if (-not (Test-Path $msbuildLib)) {
$sdkFolder = Get-ChildItem $sdkFolderBase -Directory |
Where-Object Name -Match '\d+\.\d+\.\d+' |
Sort-Object { [version]$PSItem.Name } -Descending |
Select-Object -First 1 -ExpandProperty FullName
$msbuildLib = Join-Path $sdkFolder -ChildPath Microsoft.Build.dll
}
Push-Location $sdkFolder @FailOnError
$oldCurrentDirectory = [Environment]::CurrentDirectory
[Environment]::CurrentDirectory = $sdkFolder
try {
Add-Type -Path $msbuildLib @FailOnError
$projectPath = Join-Path $SourcePath -ChildPath "$ModuleName.csproj"
$collection = [Microsoft.Build.Evaluation.ProjectCollection]::new()
$project = $collection.LoadProject($projectPath)
if (-not $BoundParameters.ContainsKey('Framework')) {
$FrameworksToProcess = $project.GetPropertyValue('TargetFrameworks') -split ';'
}
foreach ($frame in $FrameworksToProcess) {
$null = $project.SetProperty('TargetFramework', $frame)
$project.ReevaluateIfNecessary()
$FrameworkPaths[$frame] = $project.ExpandString('$(ProjectDir)$(PublishDir)')
}
$AssemblyVersion = $project.GetPropertyValue('Version')
$PackageVersion = $project.GetPropertyValue('PackageVersion')
} finally {
[Environment]::CurrentDirectory = $oldCurrentDirectory
Pop-Location
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment