title: Save file in PowerShell script access denied
body: <p>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. </p>
  
  <p>Is there a way to give the right access, without opening a window as this is done via the TFS build agent?</p>
  
  <p>Here is the script:</p>
  
  <pre><code>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)
  </code></pre>