【问题标题】:Powershell script to copy folders/files from text file用于从文本文件复制文件夹/文件的 Powershell 脚本
【发布时间】:2022-01-19 12:23:47
【问题描述】:

我正在尝试将所有文​​件夹(和所有文件)从一个文件夹复制到 Powershell 中的另一个文件夹,其中文件夹在文本文件中列出。我有一个脚本可以成功复制文件夹,但文件没有复制过来。

$file_list = Get-Content C:\Users\Desktop\temp\List.txt
$search_folder = "F:\Lists\Form601\Attachments\"
$destination_folder = "C:\Users\Desktop\601 Attachments 2021b"

foreach ($file in $file_list) {
    $file_to_move = Get-ChildItem -Path $search_folder -Filter $file -Recurse -ErrorAction SilentlyContinue -Force | % { $_.FullName}
    if ($file_to_move) {
        Copy-Item $file_to_move $destination_folder
    }
}

List.text 包含以下文件夹:
4017
4077
第4125章

【问题讨论】:

    标签: powershell directory


    【解决方案1】:

    我会在列表中的每个文件夹上使用Test-Path 来确定该文件夹是否存在。如果是,请复制。

    $folder_list        = Get-Content -Path 'C:\Users\Desktop\temp\List.txt'
    $search_folder      = 'F:\Lists\Form601\Attachments'
    $destination_folder = 'C:\Users\Desktop\601 Attachments 2021b'
    
    # first make sure the destination folder exists
    $null = New-Item -Path $destination_folder -ItemType Directory -Force
    
    foreach ($folder in $folder_list) {
        $sourceFolder = Join-Path -Path $search_folder -ChildPath $folder
        if (Test-Path -Path $sourceFolder -PathType Container) {
            # copy the folder including all files and subfolders to the destination
            Write-Host "Copying folder '$sourceFolder'..."
            Copy-Item -Path $sourceFolder -Destination $destination_folder -Recurse
        }
        else {
            Write-Warning "Folder '$folder' not found.."
        }
    }
    

    【讨论】:

    • 我之前的脚本确实将文件夹复制到了目标文件夹。所以文件夹确实存在。有没有办法在脚本运行时调试它?
    • @freebird_wr 是的,但是你在错误的地方使用了-Recurse 开关。如果这就是debug 的意思,这种方式还允许您添加控制台消息。我会在一分钟内告诉你答案。