首页 > 解决方案 > 如何用变量修改字符串?

问题描述

我正在尝试将 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

标签: powershellvariablescopystructure

解决方案


为什么不使用 -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


推荐阅读