我有一个 powershell 脚本,它可以将文件从复制$source
到$dest
,并排除某些文件类型。它可以很好地排除我的 csv 文件和 web.config 文件,但不会排除 Log 文件夹的内容。这是我的脚本,排除文件内容但不排除文件夹本身的正确语法是什么Log
?
$exclude = @('Thumbs.db','*-Log.csv','web.config','Logs/*')
Get-ChildItem $source -Recurse -Exclude $exclude | Copy-Item -Destination {Join-Path $dest $_.FullName.Substring($source.length)}
答案1
您需要设置第二个数组,其中包含要避开的路径,然后在管道中添加过滤器。以下是一些示例代码:
$exclude = @('Thumbs.db','*-Log.csv','web.config','Logs/*')
$directory = @("C:\logs")
Get-ChildItem $source -Recurse -Exclude $exclude | where {$directory -notcontains $_.DirectoryName}
答案2
您可以创建自己的递归复制函数。
function Copy-WithFilter ($sourcePath, $destPath)
{
$exclude = @('Thumbs.db', '*-Log.csv','web.config', 'Logs')
# Call this function again, using the child folders of the current source folder.
Get-ChildItem $sourcePath -Exclude $exclude | Where-Object { $_.Length -eq $null } | % { Copy-WithFilter $_.FullName (Join-Path -Path $destPath -ChildPath $_.Name) }
# Create the destination directory, if it does not already exist.
if (!(Test-Path $destPath)) { New-Item -Path $destPath -ItemType Directory | Out-Null }
# Copy the child files from source to destination.
Get-ChildItem $sourcePath -Exclude $exclude | Where-Object { $_.Length -ne $null } | Copy-Item -Destination $destPath
}
# $source and $dest defined elsewhere.
Copy-WithFilter $source $dest