-
-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathMove-Recursively.ps1
96 lines (76 loc) · 1.96 KB
/
Move-Recursively.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<#
.SYNOPSIS
Copying files and folders from one folder to another saving folders' structure
.Parameter Source
Source folder to copy content from
.Parameter Destination
Destination folder to copy content to
.Parameter Include
Include files
.Parameter Exclude
Exclude files
.Parameter Delete
Remove all copied items in the source folder recursively
.Parameter DeleteEmpty
Remove empty folders in the source folder recursively
.Parameter DeleteAll
Remove the source folder
.Example
Move-Recursively -Source "D:\FOLDER1" -Destination "d:\Folder2" -Include '*.pdf', '*.txt' -Exclude '*_out.*' -Delete
.Link
https://forum.ru-board.com/topic.cgi?forum=62&topic=30859&start=3600#4
#>
function Move-Recursively
{
[CmdletBinding()]
param
(
[string]
$Source,
[string]
$Destination,
[string[]]
$Include = "*.*",
[string[]]
$Exclude = "",
[switch]
$Delete,
[switch]
$DeleteEmpty,
[switch]
$DeleteAll
)
# Copying files saving folders' structure
# -Include & -Exclude work with -LiteralPath only in PowerShell 7
Get-ChildItem -LiteralPath $Source -Include $Include -Exclude $Exclude -Recurse -Force | Copy-Item -Destination {
$Folder = Split-Path -Path $_.FullName.Replace($Source, $Destination)
if (-not (Test-Path -LiteralPath $Folder))
{
New-Item -Path $Folder -ItemType Directory -Force
}
else
{
$Folder
}
} -Force
# Removing all copied items
if ($Delete)
{
Get-ChildItem -LiteralPath $Source -Include $Include -Exclude $Exclude -Recurse -File -Force | Remove-Item -Recurse -Force
}
# Removing empty folders
if ($DeleteEmpty)
{
Get-ChildItem -LiteralPath $Source -Recurse -Directory -Force | Sort-Object {$_.FullName.Length} -Descending | ForEach-Object -Process {
if ($null -eq (Get-ChildItem -LiteralPath $_.FullName -Recurse -Force))
{
Remove-Item -LiteralPath $_.FullName -Force
}
}
}
# Remove the source folder
if ($DeleteAll)
{
Remove-Item -LiteralPath $Source -Recurse -Force
}
}