Home > Enterprise >  Powershell, How to Delete if file exists and rename available file
Powershell, How to Delete if file exists and rename available file

Time:06-29

I have folder where I want to check if web.config exist if yes, delete it and rename available web config from somename-web.config to web.config.

For example, if I set environment dev then dev-web.config file should rename to web.config or if I set environment prod then prod-web.config file should rename to web.config

$Environment = 'Dev'
$LocalStage = 'E:\Deployment\Stage\'

#Modify web.config file as per Target Environment
Set-Location $LocalStage
if (Test-Path $LocalStage\web.config) {
 
    Write-Host "Old web config exists, Deleting the same"
    Remove-Item $LocalStage\web.config -Force
}
else
{
    $configpath = Get-ChildItem -Path $LocalStage -Filter "*$Environment*"
    rename-item -Path $LocalStage\$configpath -NewName web.config
    Write-Host "Web config stage is completed" -ForegroundColor Green -BackgroundColor Black

CodePudding user response:

I think I understand what you want to do, but instead of renaming the wanted config file, I would make a copy of it under the new name web.config, so you can always switch to another environment later.
Also, I would start off with a test to see if the wanted config file is available at all, and if not issue a warning.

Something like this:

$Environment   = 'Dev'
$LocalStage    = 'E:\Deployment\Stage'
$webConfigFile = Join-Path -Path $LocalStage -ChildPath 'web.config'
$envConfigFile = Join-Path -Path $LocalStage -ChildPath ('{0}-web.config' -f $Environment)
# test if you can find the correct config file first
if (-not (Test-Path -Path $envConfigFile -PathType Leaf)) {
    Write-Warning "Could not find file '$envConfigFile'"
}
else {
    # delete the current web.config file if found
    if (Test-Path -Path $webConfigFile -PathType Leaf) {
        Write-Host "Old web config exists, Deleting the same"
        Remove-Item -Path $webConfigFile -Force
    }
    # make a copy of the wanted environment config file and name that web.config
    Copy-Item -Path $envConfigFile -Destination $webConfigFile
    Write-Host "Web config stage is completed" -ForegroundColor Green
}

CodePudding user response:

$Environment = 'prod'
$path= "E:\Deployment\Stage"

$folder = Get-ChildItem -Path $path



if ("$folder\web.config") {
 
    Write-Host "Old web config exists, Deleting the same"
    Remove-Item $folder\web.config -Force
}

foreach($item in $folder.name){
    if($item -match $Environment){


    Rename-Item -LiteralPath "$path\$item" -NewName web.config -Force
    
     Write-Host "Web config stage is completed" -ForegroundColor Green -BackgroundColor Black
    }

}

  • Related