如何使用现有文件夹复制文件和文件夹?

时间:2018-06-28 23:45:47

标签: powershell new-item

我创建了一个脚本,用于将文件夹/子文件夹/文件从特定位置复制到我在记事本上指定的服务器列表中。

它检查是否尚未创建文件夹,它将创建该文件夹并复制文件,但是如果已经创建了文件夹,则它将停止。

但是,即使该文件夹中没有子文件夹或文件,我仍要复制较新的文件。

我当前的代码

[String] $KfxComputers = "C:\temp\Kofax Apps\servers.txt"

# This file contains the list of servers you want to copy files/folders to
$computers = get-content -Path $KfxComputers

# the folder you want to copy to the servers in the $computer variable
$sourceRoot = @("\\wdevkofx110\Kofax Software\Oracle Clients", 
            "\\wdevkofx110\Kofax Software\Kofax Capture 11")

# the destination location you want the file/folder(s) to be copied to
$destinationRoot = "C$\temp"

foreach ($computer in $computers) {

$testpath = Test-Path -Path \\$computer\$destinationRoot

if (!$testpath) 
{
    Write-Host "creating folder and copying files..." -ForegroundColor green

    New-Item -ItemType Directory -Force -Path "\\$computer\$destinationRoot"
    copy-item -Path $sourceRoot -Recurse -Destination 
    "\\$computer\$destinationRoot" -Container

} else {
        Write-Host "$computer\$destinationRoot folder already exists"
       }

}`

1 个答案:

答案 0 :(得分:0)

您可以使用Else IF

[String] $KfxComputers = "C:\temp\Kofax Apps\servers.txt"

# This file contains the list of servers you want to copy files/folders to
$computers = get-content -Path $KfxComputers

# the folder you want to copy to the servers in the $computer variable
$sourceRoot = @("\\wdevkofx110\Kofax Software\Oracle Clients", 
        "\\wdevkofx110\Kofax Software\Kofax Capture 11")

# the destination location you want the file/folder(s) to be copied to
$destinationRoot = "C$\temp"

foreach ($computer in $computers) {

$testpath = Test-Path -Path \\$computer\$destinationRoot

if (!$testpath) 
{
   Write-Host "creating folder and copying files..." -ForegroundColor green

   New-Item -ItemType Directory -Force -Path "\\$computer\$destinationRoot"
   copy-item -Path $sourceRoot -Destination 
   "\\$computer\$destinationRoot" -Container -Recurse -force 

} 

ElseIF ($testpath) {
   Write-Host "folder already exists, copying files..." -ForegroundColor green
   copy-item -Path $sourceRoot -Destination 
   "\\$computer\$destinationRoot" -Container -Recurse -force 
  }


 else {
    Write-Host "$computer\$destinationRoot folder already exists"
   }

}`