powershell - 如何用变量修改字符串?
问题描述
我正在尝试将 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
解决方案
为什么不使用 -Recurse 开关?
$source = 'C:\source'
$dest = 'C:\dest'
$extensions = @('*.pdf')
Copy-Item -Path $source -Destination $dest -Include $extensions -Force -Recurse
推荐阅读
- python - 如何为 Windows 的 Anaconda 和 Spyder 5 重新创建快捷方式?
- php - 从使用php登录的用户获取数据到html表中
- javascript - 输入类型号里面带加号、减号或“e”显示为空值,为什么?
- c++ - 将 linux 项目迁移到 Visual Studio 时在 cmake 中加载包
- flutter - 在颤动中从孩子修改父数据
- f# - 如何在 F# 中对顺序值进行分组
- python - 即使向下滚动 python selenium 后也无法单击弹出元素
- airflow-scheduler - 我的 Jinja 在 Airflow 中的输出是价值,但我更想要字符串我怎样才能得到它?
- python - 如何将 Python 2 比较函数转换为 Python 3 键函数?
- security - 2021 年存储密码的最佳方式是什么?