【问题标题】:Powershell script to Copy and Replace web.config用于复制和替换 web.config 的 Powershell 脚本
【发布时间】:2018-07-11 06:54:07
【问题描述】:

我想要一个 powershell 脚本将文件从源文件夹复制到中间文件夹,然后从中间文件夹复制到目标文件夹。在目标文件夹中已经有一个配置文件。所以想替换目标文件夹中的 web.config 文件。

这是我尝试过的:

第一次尝试:

$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 
}

第二次尝试:

$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 
}

【问题讨论】:

  • 投反对票可能是因为您粘贴了代码并说“此代码不起作用”,但您没有解释它有什么问题以及需要修复什么。您的代码似乎对中间文件夹没有任何作用。如果您已经知道源文件及其位置,为什么还要使用Get-ChildItem -RecurseCopy-Item -LiteralPath $src -Destination $dst -Force 似乎可以满足您的要求..?
  • @TessellatingHeckler 我很抱歉格式化。代码的第一部分是将文件从源文件夹复制到中间文件夹,代码的第二部分是复制和替换目标文件夹中的文件。我是PowerShell的新手。你能告诉我我应该如何解决这个问题

标签: powershell tfs powershell-2.0 tfsbuild powershell-3.0


【解决方案1】:

无需创建文件检查文件夹是否存在,使用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"
}

这将首先检查路径和文件,如果它们存在,它将复制文件。

【讨论】:

  • 此脚本会从源文件夹复制文件并替换目标文件夹中的现有文件吗?为什么在 CTABSEQA2014 之后有 2 '\\'?
  • 是的,如果需要,它会将源文件复制到目标文件夹并覆盖它。 $dst 上的额外 \\ 只是为了保留 StackOverflow 中的格式,因为它转义了关闭“它将在 PowerShell 中运行,无论是否有额外的 \
猜你喜欢
  • 1970-01-01
  • 2021-06-09
  • 2016-08-21
  • 2022-10-20
  • 1970-01-01
  • 1970-01-01
  • 2014-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多