Powershell,如何删除文件,如果文件存在,重命名可用文件



我有一个文件夹,我想检查如果web。如果存在,请删除该配置,并重新命名somename-web中的可用web配置。配置到web.config.

例如,如果我设置环境dev,那么dev-web。配置文件应该重命名为web。或者如果我设置环境prod,那么prod-web。配置文件应该重命名为web.config

$Environment = 'Dev'
$LocalStage = 'E:DeploymentStage'
#Modify web.config file as per Target Environment
Set-Location $LocalStage
if (Test-Path $LocalStageweb.config) {

Write-Host "Old web config exists, Deleting the same"
Remove-Item $LocalStageweb.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

认为我明白你想做什么,但不是重命名想要的配置文件,我会在新名称web.config下复制它,所以你以后可以随时切换到另一个环境。
另外,我会开始测试,看看所需的配置文件是否可用,如果没有发出警告。

像这样:

$Environment   = 'Dev'
$LocalStage    = 'E:DeploymentStage'
$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
}
$Environment = 'prod'
$path= "E:DeploymentStage"
$folder = Get-ChildItem -Path $path

if ("$folderweb.config") {

Write-Host "Old web config exists, Deleting the same"
Remove-Item $folderweb.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
}
}

最新更新