Powershell 在保持文件夹结构的同时复制PDF

Powershell 在保持文件夹结构的同时复制PDF,powershell,copy,directory,Powershell,Copy,Directory,因此,我试图复制所有文件夹,并保留只包含pdf的结构。我不确定是否有办法做到这一点,我已经设法让一些脚本工作 但是,当我运行它时,它会复制所有文件夹,即使其中没有PDF。我还注意到,我的脚本无法检查文件夹并在下一个目录中创建。例如: C:\temp复制一次显示C:\temp. 如果我再次运行脚本,它现在显示C:\temp\temp 下面是我的代码: $Criteria = *.pdf $Trial = c:\temp\folders.txt $Server = \\file $Path = ho

因此,我试图复制所有文件夹,并保留只包含pdf的结构。我不确定是否有办法做到这一点,我已经设法让一些脚本工作

但是,当我运行它时,它会复制所有文件夹,即使其中没有PDF。我还注意到,我的脚本无法检查文件夹并在下一个目录中创建。例如:

C:\temp复制一次显示C:\temp.
如果我再次运行脚本,它现在显示C:\temp\temp

下面是我的代码:

$Criteria = *.pdf
$Trial = c:\temp\folders.txt
$Server = \\file
$Path = homedrives\home
$des = $Path
$safe = Get-Content $Trial
$safe | ForEach-Object {
    #find drive-delimeter
    $first = $_.IndexOf("\\");
    if ($first -eq 1) {
        #stripe it
        $newdes = Join-Path -Path $des -ChildPath @($_.Substring(0,1)+$_.Substring(2))[0]    
    } else {
        $newdes = Join-Path -Path $des -ChildPath $_
    }
    $err = 0
    $fr = 0
    $folder = Split-Path -Path $newdes -Parent
    #check if folder exists"
    $void = Get-Item $folder -ErrorVariable err -ErrorAction SilentlyContinue
    if ($err.Count -ne 0) {
        #create when it doesn't
        $void = New-Item -Path $folder -ItemType Directory -Force
    }  
    #$void = Copy-Item -Path $_ -destination $newdes  -Force -Verbose
    $void = Copy-Item -Path $_ -destination $newdes -Filter $Criteria -Recurse -Force  -ErrorVariable fr -ErrorAction SilentlyContinue
    $CR = "`r`n"
    $RR = $fr[0].CategoryInfo.TargetName.ToString()
   "List of PDF's that Failed To Copy" + $CR + "--------------------------------------------------------------" + $CR + $RR | Out-file -Append $Er
    Write-Host $_
}
Write-Host $newdes

好的,看来我已经破解了它,为了将来的参考,我的代码实际上使用用户输入来确定位置,然后选择用户请求的标准,然后只复制定义了扩展名的文件。它在不复制的情况下复制文件夹结构,尽管windows的文件名限制仍然存在,但会生成一个错误日志,显示无法复制的文件。谢谢你在这件事上的帮助

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
$Server = "\\" + [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a Server to search", "Server Choice")
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
$Choice = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a File Path to search", "File Path Choice")  + "\"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
$Ext = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a File type i.e. *.PST", "Location Choice") 
#$Ext.ToUpper()
$Criteria = "*." + $Ext
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
#$FPath = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a path to copy to", "Location Choice") 
$Path = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a folder to store the data", "Path Choice") + "\"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
#$Name = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a filename", "File Name Choice")
$Search = $Server +"\"+ $Choice 
$FileName = $Path
$Info = $Path + "FileCopy.txt"
$Trial = $Path + "Folders.txt"
$Type = $Path + "$Ext's.txt"
$Er= $Path + "Failed Copying.txt"
$Trial2 = $Path + "Folders.txt"
#$Server2 = "\" + $Server
#$File = $Path + $Name
if( -Not (Test-Path -Path $Path ) )
{
    New-Item -ItemType directory -Path $Path |out-null
}
Else{
    [System.Windows.MessageBox]::Show('The directory already exists','Error','Ok','Error') 
    -ErrorAction SilentlyContinue
}
$properties = @(
    'Directory'
    ' '
    'Name'
    ' '
    @{
        Label = 'Size'
        Expression = {
            if ($_.Length -ge 1GB)
            {
                '{0:F2} GB' -f ($_.Length / 1GB)
            }
            elseif ($_.Length -ge 1MB)
            {
                '{0:F2} MB' -f ($_.Length / 1MB)
            }
            elseif ($_.Length -ge 1KB)
            {
                '{0:F2} KB' -f ($_.Length / 1KB)
            }
            else
            {
                '{0} bytes' -f $_.Length
            }
        }
        }
        $result = Get-ChildItem -Path $Search -Recurse -Include $Criteria -ErrorAction SilentlyContinue
  ) | Out-Null
  $Result
#Get-ChildItem -Path $Search -Recurse -Include *.pst -ErrorAction SilentlyContinue |
$Folders = (get-childitem -Path $Search | where-object { $_.PSIsContainer }).Count

If (Test-Path $Search) {
    <#Write-Host
    Write-Host "Listing All  Found In $Path" -ForegroundColor "Yellow"
    Write-Host "=========================================" -ForegroundColor "Yellow"#>

    Add-Type -assembly System.Windows.Forms

    ## -- Create The Progress-Bar
    $ObjForm = New-Object System.Windows.Forms.Form
    $ObjForm.Text = "Progress-Bar of searched folders"
    $ObjForm.Height = 100
    $ObjForm.Width = 500
    $ObjForm.BackColor = "White"

    $ObjForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
    $ObjForm.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen

    ## -- Create The Label
    $ObjLabel = New-Object System.Windows.Forms.Label
    $ObjLabel.Text = "Starting. Please wait ... "
    $ObjLabel.Left = 5
    $ObjLabel.Top = 10
    $ObjLabel.Width = 500 - 20
    $ObjLabel.Height = 15
    $ObjLabel.Font = "Tahoma"
    ## -- Add the label to the Form
    $ObjForm.Controls.Add($ObjLabel)

    $PB = New-Object System.Windows.Forms.ProgressBar
    $PB.Name = "PowerShellProgressBar"
    $PB.Value = 0
    $PB.Style="Continuous"

    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Width = 500 - 40
    $System_Drawing_Size.Height = 20
    $PB.Size = $System_Drawing_Size
    $PB.Left = 5
    $PB.Top = 40
    $ObjForm.Controls.Add($PB)

    ## -- Show the Progress-Bar and Start The PowerShell Script
    $ObjForm.Show() | Out-Null
    $ObjForm.Focus() | Out-NUll
    $ObjLabel.Text = "Starting. Please wait ... "
    $ObjForm.Refresh()

    Start-Sleep -Seconds 1
 Out-Null
    ## -- Execute The PowerShell Code and Update the Status of the Progress-Bar

    $result = Get-ChildItem -Path $Search -Recurse -Include $Criteria -ErrorAction SilentlyContinue 
    $Counter = 0
    ForEach ($Item In $Result) {
        ## -- Calculate The Percentage Completed
        $Counter++
        [Int]$Percentage = ($Counter/$Result.Count)*100
        $PB.Value = $Percentage
        $ObjLabel.Text = "Scanning $Folders Folders For $Criteria in $Search"
        #$ObjLabel.Text = "Found $counter $Criteria in $Search"
        $ObjForm.Refresh()
        Start-Sleep -Milliseconds 150
        # -- $Item.Name
        #"`t" + $Item.Path

    }

    $ObjForm.Close()
    #Write-Host "`n"
}
Else {
    #Write-Host
    #Write-Host "`t Cannot Execute The Script." -ForegroundColor "Yellow"
    #Write-Host "`t $Search Does Not Exist in the System." -ForegroundColor "Yellow"
    #Write-Host
}
Out-Null
Sort-Object -Property DirectoryName |

Format-Table -Property $properties |

out-file $Info



$Search| out-file -Append $Trial 
#$Search | Out-File -Append $Trial2


$result | out-file -Append $Info

$result | Select Name | out-file -Append $Type
$CR = "`r`n"
"List of PDF's that Failed To Copy" + $CR + $CR + "--------------------------------------------------------------" | Out-file $Er
$des = $Path
#$PDFs= get-content $Type
$safe = Get-Content $Trial
#$Ten = @($Criteria)
$safe | ForEach-Object{
    #find drive-delimeter
    $first=$_.IndexOf("\\");

    if($first -eq 0){
        #stripe it
    $newdes=Join-Path -Path $des -ChildPath @($_.Substring(0,1)+$_.Substring(2))[0]    
        }
        $newdes=Join-Path -Path $des -ChildPath $_
    $err=0
    $fr=0
    $folder=Split-Path -Path $newdes -Parent
    $folders=Split-Path -Path $newdes -leaf
    #$fy = $folder + "\" +$folders
    #check if folder exists"
   $void=Get-Item $newdes -ErrorVariable err  -ErrorAction SilentlyContinue #-verbose
   If(!(Test-Path -Path $newdes) ){
    $err=1
   }
     if($err.Count -ne 0){
        #create when it doesn't
        $void=New-Item -Path $folder -ItemType Directory #-verbose
        } 
            #$void=Copy-Item -Path $_ -destination $newdes  -Force -Verbose
            $void=Copy-Item -Path $_ -destination $folder -Filter $Criteria -Recurse -Container -Force -ErrorVariable fr  -ErrorAction SilentlyContinue -verbose
            write-host "------------------------------------------------------- Break -------------------------------------------------------" -ForegroundColor Green
            foreach($re in $fr){
            $RR = $re[0].CategoryInfo.TargetName.ToString()
            $X5 = $re[0].CategoryInfo.Reason.ToString()
            $X6 = $re[0].TargetObject.DirectoryName.ToString()
            $X6 + $CR + $X5 + "---" + $RR + $CR | Out-file -Append $Er
            }
    write-host "`n" $_
    }
    write-host "`n------------------------------------------------------- End of Script -------------------------------------------------------" -ForegroundColor Blue`
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')| Out Null-错误操作停止
$Server=“\\”+[Microsoft.VisualBasic.Interaction]::输入框(“请选择要搜索的服务器”,“服务器选择”)
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')| Out Null-错误操作停止
$Choice=[Microsoft.VisualBasic.Interaction]::InputBox(“请选择要搜索的文件路径”,“文件路径选择”)+“\”
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')| Out Null-错误操作停止
$Ext=[Microsoft.VisualBasic.Interaction]::InputBox(“请选择一种文件类型,即。*.PST”,“位置选择”)
#$Ext.ToUpper()
$Criteria=“*”+$Ext
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')| Out Null-错误操作停止
#$FPath=[Microsoft.VisualBasic.Interaction]::InputBox(“请选择要复制到的路径”,“位置选择”)
$Path=[Microsoft.VisualBasic.Interaction]::InputBox(“请选择一个文件夹来存储数据”,“路径选择”)+“\”
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')| Out Null-错误操作停止
#$Name=[Microsoft.VisualBasic.Interaction]::InputBox(“请选择文件名”,“文件名选择”)
$Search=$Server+“\”+$Choice
$FileName=$Path
$Info=$Path+“FileCopy.txt”
$Trial=$Path+“Folders.txt”
$Type=$Path+“$Ext.txt”
$Er=$Path+“复制.txt失败”
$Trial2=$Path+“Folders.txt”
#$Server2=“\”+$Server
#$File=$Path+$Name
if(-Not(测试路径-路径$Path))
{
新项目-项目类型目录-路径$Path | out null
}
否则{
[System.Windows.MessageBox]::Show('目录已存在'、'Error'、'Ok'、'Error')
-错误动作持续不断
}
$properties=@(
“目录”
' '
“姓名”
' '
@{
标签='Size'
表达式={
如果($\长度-ge 1GB)
{
“{0:F2}GB'-f($\长度/1GB)
}
elseif($\长度-ge 1MB)
{
'{0:F2}MB'-f($\长度/1MB)
}
elseif($\长度-ge 1KB)
{
“{0:F2}KB'-f($\长度/1KB)
}
其他的
{
“{0}字节”-f$\长度
}
}
}
$result=Get ChildItem-Path$Search-Recurse-Include$Criteria-ErrorAction SilentlyContinue
)|输出为空
$Result
#Get ChildItem-Path$Search-Recurse-Include*.pst-ErrorAction SilentlyContinue|
$Folders=(get childitem-路径$Search | where对象{$\ PSIsContainer})。计数
If(测试路径$Search){
添加类型-assembly System.Windows.Forms
##--创建进度条
$ObjForm=新对象System.Windows.Forms.Form
$ObjForm.Text=“搜索文件夹的进度条”
$ObjForm.Height=100
$ObjForm.Width=500
$ObjForm.BackColor=“白色”
$ObjForm.FormBorderStyle=[System.Windows.Forms.FormBorderStyle]::FixedSingle
$ObjForm.StartPosition=[System.Windows.Forms.FormStartPosition]::中心屏幕
##--创建标签
$ObjLabel=新对象System.Windows.Forms.Label
$ObjLabel.Text=“正在启动。请稍候…”
$ObjLabel.Left=5
$ObjLabel.Top=10
$ObjLabel.Width=500-20
$ObjLabel.Height=15
$ObjLabel.Font=“Tahoma”
##--将标签添加到表单中
$ObjForm.Controls.Add($ObjLabel)
$PB=新对象System.Windows.Forms.ProgressBar
$PB.Name=“PowerShellProgressBar”
$PB.Value=0
$PB.Style=“连续”
$System\U Drawing\U Size=新对象System.Drawing.Size
$System\图纸\尺寸.宽度=500-40
$System\图纸\尺寸高度=20
$PB.Size=$System\U Drawing\U Size
$PB.Left=5
$PB.Top=40
$ObjForm.Controls.Add($PB)
##--显示进度条并启动PowerShell脚本
$ObjForm.Show()| Out Null
$ObjForm.Focus()| Out NUll
$ObjLabel.Text=“正在启动。请稍候…”
$ObjForm.Refresh()
开始睡眠-秒1
出空
##--执行PowerShell代码并更新进度条的状态
$result=Get ChildItem-Path$Search-Recurse-Include$Criteria-ErrorAction SilentlyContinue
$Counter=0
ForEach($Result中的项目){
##--计算完成的百分比
美元柜台++
[Int]$Percentage=($Counter/$Result.Count)*100
$PB.Value=$Percentage
$ObjLabel.Text=“在$Search中扫描$Folders文件夹中的$Criteria”
#$ObjLabel.Text=“在$Search中找到$counter$条件”
$ObjForm.Refresh()
开始睡眠-150毫秒
#--$Item.Name
#“`t”+$Item.Path
}
$ObjForm.Close()
#写入主机“`n”
}
否则{
#写主机
#写入主机“`t无法执行脚本。”-ForegroundColor“黄色”
#写入主机“`t$Search在系统中不存在。”-ForegroundColor“黄色”
#写主机
}
出空
排序对象-属性目录名称