Search code examples
powershelltfspowershell-2.0tfsbuildpowershell-3.0

Powershell script to Copy and Replace web.config


I want a powershell script to copy the file from source to intermediate folder and then from intermediate folder to destination folder. In the destination folder there will already be a config file. So want to replace the web.config file in destination folder.

This is what I tried:

First attempt:

$src = "C:\Websites\CTABS\CTABSEQA2014\Web.config" 
$dst = "C:\2014_VCI_TEMP\" 

Get-ChildItem $src -Filter "txt.*.test.*" -Recurse | % { 
    #Creates an empty file at the destination to make sure that subfolders exists 
    New-Item -Path $_.FullName.Replace($src,$dst) -ItemType File -Force 
    Move-Item -Path $_.FullName -Destination $_.FullName.Replace($src,$dst) -Force 
}

Second attempt:

$src = "C:\2014_VCI_TEMP\Web.config" 
$dst = "C:\Websites\CTABS\CTABSEQA2014\"

Get-ChildItem $src -Filter "txt.*.test.*" -Recurse | % { 
    #Creates an empty file at the destination to make sure that subfolders exists 
    New-Item -Path $_.FullName.Replace($src,$dst) -ItemType File -Force 
    Move-Item -Path $_.FullName -Destination $_.FullName.Replace($src,$dst) -Force 
}

Solution

  • No need to create a file to check if the folder exists, just use Test-Path:

    $src = "C:\2014_VCI_TEMP\Web.config" 
    $dst = "C:\Websites\CTABS\CTABSEQA2014\\"
    
    if((Test-Path $dst) -and (Test-Path $src))
    {
        Copy-Item -LiteralPath $src -Destination $dst -Force
    }
    else
    {
        Write-Output "Folder or file does not exist"
    }
    

    This will check the path and the file first, if they exist, it will copy the file.