我想复制文件夹的内容并排除“Cookie”。
我已经尝试了一些类似问题的解决方案,但它们对我不起作用。
$excludes = "Cookies"
New-Item -Path $newdir -Type Directory -Name "AppData"
Copy-Item -Path (Get-Item -Path $path"\AppData\*" -Exclude ($excludes)).FullName -Destination $newdir"\AppData" -Recurse -Force我只想复制目录中的内容,不包括1个文件夹。
我使用的是PowerShell 5.1版
发布于 2021-11-14 16:17:46
我为日常使用编写了这段代码,并将其打包到脚本模块中,它维护所有的目录结构并支持通配符:
function Copy-Folder {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[String]$FromPath,
[Parameter(Mandatory)]
[String]$ToPath,
[string[]] $Exclude
)
if (Test-Path $FromPath -PathType Container) {
New-Item $ToPath -ItemType Directory -ErrorAction SilentlyContinue | Out-Null
Get-ChildItem $FromPath -Force | ForEach-Object {
# avoid the nested pipeline variable
$item = $_
$target_path = Join-Path $ToPath $item.Name
if (($Exclude | ForEach-Object { $item.Name -like $_ }) -notcontains $true) {
if (Test-Path $target_path) { Remove-Item $target_path -Recurse -Force }
Copy-Item $item.FullName $target_path
Copy-Folder -FromPath $item.FullName $target_path $Exclude
}
}
}
}只需调用Copy-Folder -FromPath 'fromDir' -ToPath 'destDir' -Exclude Cookies
可以省略-FromPath和-ToPath,
Copy-Folder fromDir destDir -Exclude Cookies
发布于 2019-07-24 17:47:21
此代码无效的Get-Item -Path $path"\AppData\*",PowerShell无法连接变量和字符串。将代码更改为:
$excludes = "Cookies"
New-Item -Path $newdir -Type Directory -Name "AppData"
# Join the path correctly
$joinedPath = Join-Path $path "AppData\*"
Copy-Item -Path (Get-Item -Path $joinedPath -Exclude ($excludes) -Directory).FullName -Destination $newdir"\AppData" -Recurse -Force仅供参考:请注意,仅当通配符包含在路径中时,-Exclude开关才有效(问题中正确地完成了此操作)。Source
-Exclude
以字符串数组的形式指定此cmdlet在操作中排除的一个或多个项。此参数的值限定Path参数。输入路径元素或模式,如*.txt。允许使用通配符。仅当命令包含项目内容时,排除参数才有效,例如C:\Windows*,其中通配符指定C:\Windows目录的内容。
希望这能有所帮助。
发布于 2019-07-24 23:56:03
$destName = "C:\Test Folder"
$target = "Folder"
$exclude = "Bad Folder"
Get-ChildItem $target | Where-Object {$_.BaseName -notin $exclude} | Copy-Item -Destination $destName -Recurse -Force这应该是可行的。如果要排除多个文件夹或文件,可以将排除设置为多个名称。如果您只想要文件,则需要在Get-ChildItem中添加-Directory。Copy-Item and exclude folders我基于前面的回答
https://stackoverflow.com/questions/57178111
复制相似问题