Using Powershell to checkin zip file to TFS - powershell

My build server is doing all the steps necessary to build a zip of the new website. I would like to add a step to checkin zipfile to TFS. I have created a ps1 file to perform the checkin. I am running it in ISE so there is no dependency on having TeamCity. Here are the errors that I am seeing.
No matter how I do workspace.GET, it does not get the latest code
from the server.
Even when I change a file on the hard drive it
does not see changes.
Because no changes are detected the zip is
not checked in to TFS.
Here is the code....
#============================================================================
# Method to check in all zip files
#
# Example of WorkingDir passed in
# "D:\TeamCity\buildAgent\work\281509782e84e723\Powershell"
#
# Example of where freshly created zips live
# "D:\TeamCity\buildAgent\work\281509782e84e723\Zips"
#
# this script is based on
# From https://github.com/mmessano/PowerShell/blob/master/TFSCheckIn.ps1
# From http://stackoverflow.com/questions/25917753/check-a-file-into-tfs-using-powershell
# from http://lennartjansson2.wordpress.com/2011/10/13/setting-tfs-vcs-security-with-ps-2/
#
#============================================================================
function StackOverflow {
Param( [Parameter(Mandatory=$true)][string]$WorkingDir )
Write-BuildLog "Inside StackOverflow"
# Get the direcory where new zips where built
$NewZipFiles = $WorkingDir + "\..\Zips\*"
# This is the url to the TFS server + Project collection
$tfsServer = "YourServerAndCollection";
# this is the full path on server where zips live
# You need to start description with $
$tfsServerPath = "$/MyProject/FullPathToDirwithZips"
# Where on local hard drive should files from TFS be placed
$LocalCkoutDir = "D:\MyLocalHDPath"
# Debug print var to verify correct
Write-BuildLog "NewZipFiles => $NewZipFiles"
Write-BuildLog "tfsServer => $tfsServer"
Write-BuildLog "tfsServerPath => $tfsServerPath"
Write-BuildLog "LocalCkoutDir => $LocalCkoutDir"
# Get the TeamCity build number
#$VarName = "BUILD_NUMBER"
#$TeamCityVersionNbr = (get-item env:$VarName).Value
$TeamCityVersionNbr = "MyProject_03_02_81"
Write-BuildLog "Version Nbr $TeamCityVersionNbr"
$CheckInComment = "Check in zips for $BuildNumber"
# Load the assemblies needed for TFS:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.VersionControl.Common") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.VersionControl.Client") | out-null
#Set up connection to TFS Server and get version control
$tfs = [Microsoft.TeamFoundation.Client.TeamFoundationServerFactory]::GetServer($tfsServer)
$versionControlType = [Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]
$versionControlServer = $tfs.GetService($versionControlType)
#check to see if workspace already exists. If it does delete it.
$WorkSpaceNameForCheckIn = "TeamCityWorkspace"
$ThisBoxName = [System.Environment]::MachineName
$test = $versionControlServer.QueryWorkspaces( $WorkSpaceNameForCheckIn, $versionControlServer.AuthenticatedUser, $ThisBoxName )
if ( $test.length -eq 1 )
{
$test[0].Delete()
}
# Generate a workspace
$workspace = $versionControlServer.CreateWorkspace($WorkSpaceNameForCheckIn);
# Map Server path to local path
$workspace.Map($tfsServerPath, $LocalCkoutDir)
# DEBUG: build filename of a zip.
# We will overwrite this file to test the get
$file = "AZipFileThatExists.zip"
$filePath = $LocalCkoutDir + "\" + $file
"hello world" | Out-File $filePath
# I tried the simple get but it does not get
# Get the zip files from the server to local directory
$getstatus = $workspace.Get()
# Csharp way of doing it
#workspace.Map(projectPath, workingDirectory);
# var myItemSpec = new ItemSpec(projectPath, RecursionType.Full);
#GetRequest request = new GetRequest(myItemSpec, VersionSpec.Latest);
#GetStatus status = workspace.Get(request, GetOptions.GetAll | GetOptions.Overwrite); // this line doesn't do anything - no failures or er
# This does not work either
# Powershell checkout the file. Overwrite if file exists. Get even if TFS thinks it is up to date.
$NewItemSpec = New-Object Microsoft.TeamFoundation.VersionControl.Client.ItemSpec ( $tfsServerPath, [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full)
$NewRequest = New-Object Microsoft.TeamFoundation.VersionControl.Client.GetRequest( $NewItemSpec, [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest)
$getstatus = $workspace.Get( $NewRequest, [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::GetAll -bOr [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::Overwrite )
# I have not tested the rest of this since the "get" does not work.
# Mark the files before we refresh them with new zips
$result = $workspace.PendEdit($LocalCkoutDir)
# Copy zips that where built by TeamCity to checkin direcory
Copy-Item $NewZipFiles $LocalCkoutDir -force -recurse
# check if we have some pending changes. If we do checkin changes
$pendings = $workspace.GetPendingChanges();
if($pendings.Count -gt 0){
$result = $workspace.CheckIn($pendings, $CheckInComment);
Write-BuildLog "Changes where checked in";
}
else
{
Write-BuildLog "No changes found";
}
# delete the workspace
$result = $workspace.Delete()
}
#============================================================================
# Write to the build log
#============================================================================
function Write-BuildLog {
param( [Parameter( Mandatory=$true)] $Message
)
write-host $Message
#write-host "##teamcity[message text='" + $Message + "']"
}
$myDir = Split-Path -Parent $MyInvocation.MyCommand.Path
StackOverflow $myDir

use the tf command line
Example for checkin:
cd C:\TFS\Arquitectura
%ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE\TF.exe checkin $/Arquitectura/Main /recursive
On Windows x64
"%ProgramFiles(x86)%\Microsoft Visual Studio 10.0\Common7\IDE\TF.exe" checkin $/Arquitectura/Main /recursive
See for more information on the tf commandline: http://msdn.microsoft.com/en-us/library/z51z7zy0(v=VS.90).aspx
Only learning curve about use tf.exe with Powershell. Maybe source code sample is required.
Source: Scripting TFS Command Line for Get Latest Version, Check Out and Check in, programmatically

Related

Need a PowerShell command to update the .NET Core Project's (Assembly or File) version

Using PowerShell script, I am able to read the Team Foundation Server workspace version numbers.
Now I would like to update the .NET Core Project's Assembly/or/File version in its properties...
I am looking for a PowerShell command that updates properties of the project .. is that even possible?
Or a command that would update one of the properties in the appsettings.json file's data
Ex:
"AssemblyVersion": "12345"
Thank you for taking the time to look at this if you are looking to help me
...and Sorry if you are looking for a solution and there is none yet
Perry
p.s.
What I am trying to achieve is the equivalent of Tortoise's "subwcrev" command to update the "AssemblyInfoTemplate"
You can achieve this by using the .NET framework's System.Reflection.AssemblyInfo class, which provides a way to modify the AssemblyInfo file in a project.
e.g
$assemblyInfoFile = 'path\to\AssemblyInfo.cs'
$assemblyVersion = '1.0.0.0'
$fileVersion = '1.0.0.0'
$assemblyInfoContent = Get-Content $assemblyInfoFile
$assemblyInfoContent = $assemblyInfoContent -replace 'AssemblyVersion\("[^"]*"\)', "AssemblyVersion(`"$assemblyVersion`")"
$assemblyInfoContent = $assemblyInfoContent -replace 'AssemblyFileVersion\("[^"]*"\)', "AssemblyFileVersion(`"$fileVersion`")"
Set-Content $assemblyInfoFile $assemblyInfoContent
Once you have updated the AssemblyInfo file, you should be able to see the changes reflected in the project properties in Visual Studio or any other development environment you are using.
Yé!
I've done it.
And I would like to add that I got most of my info from this site ;)
See the code attached c/w comments
### TFS HISTORY
Set-Alias tfs "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe"
######### some commands I tried that I want to keep
### tfs history . /r /noprompt /stopafter:1 /version:W | Out-File -FilePath C:\temp\OUTPUT.txt
### Get-Content "C:\temp\OUTPUT.txt" -tail 1 | Out-File -FilePath "C:\temp\output.csv"
### $variable = Get-Content "C:\temp\OUTPUT.txt" -tail 1 ### gets the last line
#==========================================================================
$variable = tfs history . /r /noprompt /stopafter:1 /version:W # get the version of tfs
########## the three lines below are the result of the "tfs history" command
# Changeset User Date Comment
# --------- ----------------- ---------- --------------
# 97504 Dorion, Perry 2023-02-09 v#
# what I need is the "97504" number
$vlinearray = $variable.split("`r`n") # split into lines
$vspacearray = $vlinearray[$vlinearray.Length -1].split(" ") # split the last line into space separated strings
######### for debugging purposes
# Write-Output $vspacearray[0] #get the first string of the last line
###################################################
############ SAVES to appsettings.json ############
### not being used
# $pathToJson = "C:\Users\PDorion\Documents\DevNETCore\PNR\PEA\appsettings.json"
# $a = Get-Content $pathToJson | ConvertFrom-Json
# $a.AssemblyVersion = $vspacearray[0]
# $a | ConvertTo-Json | set-content $pathToJson
### I needed a way to find the path of the ruinning script; mine differs from my co-workers who work on the same project
### gets path of this script i.e. "C:\Users\PDorion\Documents\DevNETCore\PNR\PEA\"
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition;
$scriptName = "\PEA.csproj";
### get the value from TFS HISTORY
### DOTIFY the 5 digit number ==> #.#.#.## format
### our TFS version numbers are too big and do not jive well with Assembly number type
$splitval = $vspacearray[0].ToCharArray()
$Result = ""
$dot = ""
$dotcnt = 0
foreach ($num in $splitval) {
$Result = "$Result$dot$num"
$dotcnt++
if ($dotcnt -lt 4 ) {
$dot = "."
}else{
$dot = ""
}
}
### Write-Output "Result $Result"
$projFile = "$scriptPath$scriptName";
### get Project xml content i.e. the properties
$config = (Get-Content $projFile) -as [Xml];
$ns = New-Object System.Xml.XmlNamespaceManager($config.NameTable);
$ns.AddNamespace("cs", $config.DocumentElement.NamespaceURI);
### the following is ugly but it works
$config.DocumentElement.SelectNodes("//cs:AssemblyVersion", $ns) | % {
$node = $_;
$node.InnerText = $Result;
}
$config.DocumentElement.SelectNodes("//cs:FileVersion", $ns) | % {
$node = $_;
$node.InnerText = $Result;
}
### save the sucker
$config.Save($projFile);

Visual studio Build Task Issue for PowerShell inline task - Azure

I am running a vsts build inline PowerShell script task to create package for Azure cloud service. It works fine and create package file from my local machine, but when I try to run from VSTS PowerShell inline task it gives error :
##[error]Cannot find path ‘D:\a_tasks\InlinePowershell_31f040e5-e040-4336-878a-59a493355534\1.1.6\ServiceConfiguration.Cloud.Test.cscfg’ because it does not exist.
Here is my PowerShell inline script below, It fails on the following line:
Copy-Item $serviceConfigurationPath $packageOutDir
I really appreciate your help on this.
Thanks,
# This is the VSTS repository path
$workingDirectory = “$/DevCodeBase/ToolDevBranch1.33”
$webProjectName = “WebRole1”
$cloudProjectName = ‘ProjAzureDeployment’
$evv =’Test’
$cppack = ‘C:\Program Files\Microsoft SDKs\Azure\.NET SDK\v2.9\bin\cspack.exe’
$solutionDir = [string]::Format(“{0}”, $workingDirectory)
$webDir = [string]::Format(“{0}\{1}”, $workingDirectory, $webProjectName)
$packageOutDir = [string]::Format(“{0}\{1}”, $workingDirectory, $cloudProjectName)
$rolePropertyFile = [string]::Format(“{0}\{1}\{2}”, $workingDirectory, $cloudProjectName, “roleproperties.txt”)
# Create Role Properties File – This property file specifies the .Net framework against which webrole is going to run.
New-Item $rolePropertyFile -Type file -Force -Value “TargetFrameWorkVersion=v4.5” | Out-Null
New-Item $packageOutDir -Type directory -Force | Out-Null
# CSPack command Definition
$serviceDefinitionPath = [string]::Format(“{0}\{1}\ServiceDefinition.csdef”, $solutionDir, $cloudProjectName)
if ($evv -eq “Test”){
$serviceConfigurationPath = “ServiceConfiguration.Cloud.Test.cscfg”
}
else
{
$serviceConfigurationPath = [string]::Format(“{0}\{1}\ServiceConfiguration.Cloud.cscfg”, $solutionDir, $cloudProjectName)
}
$serviceRole = [string]::Format(“/role:{0};{1}”, $webProjectName, $webDir)
$rolePropertiesFile = [string]::Format(“/rolePropertiesFile:{0};{1}”, $webProjectName, $rolePropertyFile)
$sites = [string]::Format(“/sites:{0};Web;{1}”, $webProjectName, $webDir)
$packageOutput = [string]::Format(“/out:{0}\{1}.cspkg”, $packageOutDir, $cloudProjectName)
# $packageOutput = [string]::Format(“{0}\{1}.cspkg”, $packageOutDir, $cloudProjectName)
Write-Host $packageOutput
Write-Host $serviceConfigurationPath
# Build CSPKG file
& “C:\Program Files\Microsoft SDKs\Azure\.NET SDK\v2.9\bin\cspack.exe” $serviceDefinitionPath $serviceRole $rolePropertiesFile $sites $packageOutput /useCtpPackageFormat | Out-Null
Write-Host $serviceDefinitionPath
Write-Host $serviceRole
Write-Host $rolePropertiesFile
Write-Host $sites
Write-Host $packageOutput
Write-Host ‘before copy’
# Copy configuration file
Copy-Item $serviceConfigurationPath $packageOutDir
# Remove Role Properties File
Remove-Item -Path $rolePropertyFile -Force | Out-Null
In the VSTS task you'll have to specify an absolute path, otherwise the script will look in the temporary directory created for your inline powershell script.
For instance, you could supply the path to the file as a parameter like
-filepath "$(System.DefaultWorkingDirectory)\Solution\config.json"
(For a list of the variables you can use, have a peek here)
If you want to keep using a relative path, you can move to a file based (ie non-inline) script and use a relative path to that.

Error when using powershell script to generate changelog file from Teamcity build

I am using the following script to generate a changelog from teamcity builds.
<#
.SYNOPSIS
Generates a project change log file.
.LINK
Script posted over:
http://open.bekk.no/generating-a-project-change-log-with-teamcity-and-powershell
#>
# Where the changelog file will be created
$outputFile = "%system.teamcity.build.tempDir%\releasenotesfile_%teamcity.build.id%.txt"
# the url of teamcity server
$teamcityUrl = "%teamcity.serverUrl%"
# username/password to access Teamcity REST API
$authToken=[Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("%system.teamcity.auth.userId%:%system.teamcity.auth.password%"))
# Build id for the release notes
$buildId = %teamcity.build.id%
# Get the commit messages for the specified change id
# Ignore messages containing #ignore
# Ignore empty lines
Function GetCommitMessages($changeid)
{
$request = [System.Net.WebRequest]::Create("$teamcityUrl/httpAuth/app/rest/changes/id:$changeid")
$request.Headers.Add("AUTHORIZATION", "$authToken");
$xml = [xml](new-object System.IO.StreamReader $request.GetResponse().GetResponseStream()).ReadToEnd()
Microsoft.PowerShell.Utility\Select-Xml $xml -XPath "/change" |
where { ($_.Node["comment"].InnerText.Length -ne 0) -and (-Not $_.Node["comment"].InnerText.Contains('#ignore'))} |
foreach {"+ $($_.Node["user"].name) : $($_.Node["comment"].InnerText.Trim().Replace("`n"," "))`n"}
}
# Grab all the changes
$request = [System.Net.WebRequest]::Create("$teamcityUrl/httpAuth/app/rest/changes?build=id:$($buildId)")
$request.Headers.Add("AUTHORIZATION", "$authToken");
$xml = [xml](new-object System.IO.StreamReader $request.GetResponse().GetResponseStream()).ReadToEnd()
# Then get all commit messages for each of them
$changelog = Microsoft.PowerShell.Utility\Select-Xml $xml -XPath "/changes/change" | Foreach {GetCommitMessages($_.Node.id)}
$changelog > $outputFile
Write-Host "Changelog saved to ${outputFile}:"
$changelog
When I run this, the file is generated, but it is always empty. When I look at the build log I see the following error message from the powershell build step.
Can anyone tell me what is going wrong and what I need to change to make this step work?
These error observed on with teamcity version 10.
Replace Add("AUTHORIZATION", "$authToken") with
Add("AUTHORIZATION", "Basic $authToken")
These code worked for me version 10 with build number 50574.
<#
.SYNOPSIS
Generates a project change log file.
.LINK
Script posted over:
http://open.bekk.no/generating-a-project-change-log-with-teamcity-and-powershell
#>
# Where the changelog file will be created
$outputFile = "%system.teamcity.build.tempDir%\releasenotesfile_%teamcity.build.id%.txt"
# the url of teamcity server
$teamcityUrl = "%teamcity.serverUrl%"
# username/password to access Teamcity REST API
$authToken=[Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("%system.teamcity.auth.userId%:%system.teamcity.auth.password%"))
# Build id for the release notes
$buildId = %teamcity.build.id%
# Get the commit messages for the specified change id
# Ignore messages containing #ignore
# Ignore empty lines
Function GetCommitMessages($changeid)
{
$request = [System.Net.WebRequest]::Create("$teamcityUrl/httpAuth/app/rest/changes/id:$changeid")
$request.Headers.Add("AUTHORIZATION", "$authToken");
$xml = [xml](new-object System.IO.StreamReader $request.GetResponse().GetResponseStream()).ReadToEnd()
Microsoft.PowerShell.Utility\Select-Xml $xml -XPath "/change" |
where { ($_.Node["comment"].InnerText.Length -ne 0) -and (-Not $_.Node["comment"].InnerText.Contains('#ignore'))} |
foreach {"+ $($_.Node["user"].name) : $($_.Node["comment"].InnerText.Trim().Replace("`n"," "))`n"}
}
# Grab all the changes
$request = [System.Net.WebRequest]::Create("$teamcityUrl/httpAuth/app/rest/changes?build=id:$($buildId)")
$request.Headers.Add("AUTHORIZATION", "$authToken");
$xml = [xml](new-object System.IO.StreamReader $request.GetResponse().GetResponseStream()).ReadToEnd()
# Then get all commit messages for each of them
$changelog = Microsoft.PowerShell.Utility\Select-Xml $xml -XPath "/changes/change" | Foreach {GetCommitMessages($_.Node.id)}
$changelog > $outputFile
Write-Host "Changelog saved to ${outputFile}:"
$changelog

Get the latest checkin files from a tfs folder using powershell

Hi i am actually new to powershell. I am trying to do ETL database deployment, so i need all the files with in the tfs folder after a given time. I established the connection with the tfs but i am able to download the files but if a file has two check-ins i am getting the file with the previous checkin and not the latest
My code:
$TfsUrl = "http://tfs2013-xxx02.ad.xxx.com:8080/tfs/abcd-xxx243"
# Load TFS assemblies for connecting to the TFS server
Add-Type -Path "E:\Microsoft Visual Studio 14.0\Common7\IDE\TestAgent\Microsoft.TeamFoundation.Client.dll"
Add-Type -Path "E:\Microsoft Visual Studio 14.0\Common7\IDE\TestAgent\Microsoft.TeamFoundation.Common.dll"
Add-Type -Path "E:\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\4qvjm2or.ipa\Microsoft.TeamFoundation.Lab.Client.dll"
Add-Type -Path "E:\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\4qvjm2or.ipa\Microsoft.TeamFoundation.Lab.Common.dll"
Add-Type -Path "E:\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\4qvjm2or.ipa\Microsoft.TeamFoundation.VersionControl.Client.dll"
#Get TFS Instance
$Tfs = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($TfsUrl)
# use the account credentials of the process running the script
try
{
$Tfs.EnsureAuthenticated()
Write-Output "TFS Connection is successful"
}
catch
{
Write-Output "Error trying to connect to tfs server. Check your tfs permissions and path: $_ "
Exit(1)
}
#Write-Message $LogFileName "THIS IS INSIDE Connect-ToTFS"
#Write-Message $LogFileName "TFS IS $Tfs"
$DeploymentFilePath= "$/xxxx/FutureReleases/Database/ReportingETLs"
$TFSInstance = $Tfs.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$LatestVersion = [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest
$RecursionType = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
$DateFrom = "D2016-10-08T01:59"
# Get the From and To date-time in version format to be passed to TFS API
$VersionFrom = $null
$VersionFrom = [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::ParseSingleSpec($DateFrom, "")
$FileHistory = #($TFSInstance.QueryHistory($DeploymentFilePath,$LatestVersion,0,$RecursionType,$null,$null,$null,[int32]::MaxValue, $true ,$true, $true))
#Write-Output "Filehistory is: $FileHistory"
#$ChangeSetCount = $FileHistory.Count
#Write-Output "ChangeSetCount is: $ChangeSetCount"
$TFSGetFullPath = "E:\temp\"
$chArray = #()
$checkin =""
foreach ($history in $FileHistory)
{
foreach ($change in $history.Changes)
{
foreach ($item in $change.item)
{
if($item.CheckinDate -gt $VersionFrom.Date)
{
$chArray += $history.ChangesetId
}
}
}
}
Write-Output "ChangesetArray is: $chArray"
foreach ($ch in $chArray)
{
foreach ($lastdeployedHistory in $FileHistory)
{
if($lastdeployedHistory.ChangesetId -eq $ch)
{
foreach ($workitem in $lastdeployedHistory.Changes)
{
$workitem.Item.DownloadFile([IO.Path]::GetFullPath($TFSGetFullPath) + $workitem.Item.ServerItem.Split('/')[$workitem.Item.ServerItem.Split('/').Length - 1]);
}
}
}
}
This is caused by the object order in $chArray. The changeset in $chArray is ordered from new to old. When you download the file, it is downloading the new file first and then download the older file.
For example, there are two changesets for one file: 111 and 112, with the code Write-Output "ChangesetArray is: $chArray" in your script, you should see the output like: ChangesetArray is: 112 111. When it downloads the file, the file with 112 version is downloaded first and then 111 version which overwrite the latest version.
You can sort the array in $chArray to fix this issue:
Write-Output "ChangesetArray is: $chArray"
$sortcsarray = $chArray | Sort-Object
Write-Output "ChangesetArray is: $sortcsarray"
foreach ($ch in $sortcsarray)

Save file in PowerShell script access denied

I have a PowerShell script that is intended to modify a web config transform as a pre-build event in a build definition. I've gotten it working for the most part, however when it goes to save the updated file I am getting access denied.
Is there a way to give the right access, without opening a window as this is done via the TFS build agent?
Here is the script:
param(
[string]$buildTarget="Dev",
[string]$projectName="SalesTools"
)
$VerbosePreference = "continue"
Write-Verbose "Params: buildTarget = '$($buildTarget)', projectName = '$($projectName)'"
# Make sure path to source code directory is available
if (-not $Env:TF_BUILD_SOURCESDIRECTORY)
{
Write-Error ("TF_BUILD_SOURCESDIRECTORY environment variable is missing.")
exit 1
}
elseif (-not (Test-Path $Env:TF_BUILD_SOURCESDIRECTORY))
{
Write-Error "TF_BUILD_SOURCESDIRECTORY does not exist: $Env:TF_BUILD_SOURCESDIRECTORY"
exit 1
}
Write-Verbose "TF_BUILD_SOURCESDIRECTORY: $Env:TF_BUILD_SOURCESDIRECTORY"
$webConfig = "$($Env:TF_BUILD_SOURCESDIRECTORY)\$($buildTarget)\SalesTools.Web\$($projectName)\web.$($buildTarget).config"
#$webConfig = "$($Env:TF_BUILD_SOURCESDIRECTORY)\$($buildTarget)\SalesTools.Web\ARCTools\web.$($buildTarget).config"
Write-Verbose "File Path: $($webConfig)"
$doc = (gc $webConfig) -as [xml]
$versionNumber = $doc.SelectSingleNode('//appSettings/add[#key="versionNumber"]/#value').'#text'
Write-Verbose "Current Version Number: $($versionNumber)"
if (($versionNumber))
{
$versionInfo = $versionNumber.Split(".")
$versionIteration = $versionInfo[1]
$minorVersion = $versionInfo[2] -as [int]
$minorVersion = $minorVersion + 1
$currentIteration = Get-Iteration
$newVersionInfo = ("v: 1.$($currentIteration).$($minorVersion)")
}
else
{
Write-Error "Could not get version info from config."
exit 1
}
$doc.SelectSingleNode('//appSettings/add[#key="versionNumber"]/#value').'#text' = $newVersionInfo
$doc.Save($webConfig)
Before you read & update the web.config, try to change the "Read-Only" attribute of web.config file. Because by default, all the source files are "Read-Only".
Add this line before "$doc = ....":
attrib -R $webConfig /S