Как изменить строку с переменной? - PullRequest
0 голосов
/ 21 мая 2018

Я пытаюсь скопировать PDF-файлы с одного сервера на другой, сохраняя структуру папок. Я разработал следующий сценарий.

Я пытаюсь найти данные, содержащиеся в переменной $Server, в другой переменной $newdes и удалить их.Однако этого не происходит.Если вы проверите переменную $newdes, вы увидите, что она содержит данные, хранящиеся в $Server, которые мне нужно удалить, чтобы начать копирование.

В том виде, как она стоит в переменной $newdesсодержит

C:\Temp\ \file\homedrives\home

Может не отображаться, но я вижу двойной \ в качестве пути к файлу UNC.

Мне нужно прочитать C:\temp\homedrives\home.

Ядогадываясь из-за \ \file, что не удается запустить копию, если это так, кто-то посоветует, как заставить это работать.

Исправлено в соответствии с просьбой:

$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
  > $folder = Split-Path -Path $newdes -Parent

    $err = 0
    # 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 -Verbose
    }

    $void = Copy-Item -Path $_ -Destination $des -Force -Verbose
    #$void = Copy-Item -Path $_ -Include $Criteria -Destination $Path $Choice -Recurse -Container
    #$void = Copy-Item -Path $Files -Include $Criteria -Destination $newdes -Force -Verbose -Recurse -ErrorAction SilentlyContinue
    Write-Host $_
}
Write-Host $newdes

Ответы [ 2 ]

0 голосов
/ 22 мая 2018

ок, спасибо за помощь, теперь я решил проблему, но она представила другую.Опубликуем еще один вопрос.

Решением вышеизложенного является использование

-фильтра "* .pdf"

Ниже приведена копия моегокод

    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
Function Select-Server
    {
         param([string]$Description="Select Folder",[string]$RootFolder="Desktop")

     [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null     

     $objForm = New-Object System.Windows.Forms.FolderBrowserDialog
     $objForm.Rootfolder = $Server
     $objForm.Description = $Description
     $objForm.ShowNewFolderButton = $false
     $Show = $objForm.ShowDialog()
     If ($Show -eq "OK")
     {
         Return $objForm.SelectedPath + "\"
     }
     Else
     {
        Write-Error "Operation cancelled by user."
     }
    }
    Function Select-FolderDialog
    {
         param([string]$Description="Select Folder",[string]$RootFolder="Desktop")

     [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null     

     $objForm = New-Object System.Windows.Forms.FolderBrowserDialog
     $objForm.Rootfolder = $RootFolder
     $objForm.Description = $Description
     $objForm.ShowNewFolderButton = $false
     $Show = $objForm.ShowDialog()
     If ($Show -eq "OK")
     {
         Return $objForm.SelectedPath
     }
     Else
     {
        Write-Error "Operation cancelled by user."
     }
    }
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$Server = "\\" + [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a Server to search", "Server Choice")
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$Choice = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a File Path to search", "File Path Choice")  + "\"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$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
#$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
#$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"
$Trial2 = $Path + "Ammended Folders.txt"
$Type = $Path + "$Ext's.txt".ToUpper()
#$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')
}
$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


$des = $Path
#$PDFs= get-content $Type
$safe = Get-Content $Trial
#$Ten = @($Criteria)
$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
    $folder=Split-Path -Path $newdes -Parent
    $err=0
    #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 -Verbose
        }  
$void=Copy-Item -Path $_ -destination $newdes -Filter $Criteria -recurse -Container -Force -Verbose -ErrorAction SilentlyContinue

    write-host $_
    }
    write-host $newdes

$ void = Copy-Item -Path $ _ -destination $ newdes -Filter $ Критерии -recurse -Container -Force -Verbose -ErrorAction SilentlyContinue

0 голосов
/ 21 мая 2018

Почему вы не используете ключ -Recurse?

$source     = 'C:\source'
$dest       = 'C:\dest'
$extensions = @('*.pdf')

Copy-Item -Path $source -Destination $dest -Include $extensions -Force -Recurse

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/copy-item?view=powershell-6

...