【发布时间】:2018-07-09 16:06:42
【问题描述】:
我目前正在使用 Powershell 进行一个项目,对此我真的不是很熟悉。我已经非常接近了,并环顾四周以使我更接近,但我对这个大时代感到难过。
目标是递归搜索一个目录中以“\_7Y_”开头的文件(这是由我编写的另一个脚本完成的,基于文件年龄),并在该文件的父目录中创建一个新的子目录,然后移动它在那里。例如,如果我有~\desktop\old\\_7Y_OldFile.txt,我希望该文件转到~\desktop\old\\_7Y_\\_7Y_OldFile.txt,并且我希望它以递归方式对每个文件执行此操作。
我的脚本当前按预期创建了文件夹,但只选择了一个新文件夹以将项目移动到其中。我认为这是由于 $child 变量只选择了一个值,因为在它移动文件后,脚本会继续执行,但在尝试查找要移动它们的文件时出错。没有手动告诉它每个父母(这个过程最终将是自动化的),我想知道可以做些什么来区分每个 $child 的移动。
我的理解也是,只要我使用-force,我不应该需要先做一个新项目,然后再做一个移动项目,但这也不是我的经验。任何帮助将不胜感激。
对于奇怪的格式和技术,我深表歉意——我一直在边学习边学习 powershell。
[CmdletBinding()]
Param(
[Parameter(mandatory=$true)]
[ValidateScript({Test-Path $_ -PathType 'any'})]
[string] $InputFilePath
)
#this sets the filepath parameter to mandatory, so you will need to input
your own filepath!
$directoryInfo = Get-ChildItem $InputFilePath -recurse | Measure-Object
$7Yno = Get-ChildItem $InputFilePath -recurse | Where-Object {$_.Name -like '_7Y_*.*'} | Measure-Object
#These are used as the conditions for the if statements
#directoryInfo gets the number of files in the directory; 7Yno gets the number of files prepended with _7Y_ in the directory
$Confirmation = Read-Host "Are you SURE you want to proceed with this operation? All selected files in the given directory will be moved to new directories! This action is irreversable. Your selected directory is $InputFilePath. Enter 'Yes' to proceed"
if ($Confirmation -eq "Yes") {
if ($directoryInfo.count -gt 0 -and $7Yno.count -gt 0){ #Check: Files in directory and files prepended with _7Y_ in directory.
$children = @((Get-ChildItem $InputFilePath -recurse |
Where-Object {$_.Name -like "_7Y_*.*"}).directory.fullname |
Get-Unique)
$Files = @(Get-ChildItem $children -recurse |
Where-Object {$_.Name -like "_7Y_*.*"})
foreach($child in $children){
$7yPath = "$child\_7Y_"
New-Item -itemtype Directory -path $7yPath -force
}
foreach($file in $Files){
Move-Item $file.fullname -destination $7yPath -force
}
}
if ($directoryInfo.count -gt 0 -and $7Yno.count -eq 0){ #Check: Files in directory, but no files prepended with _7Y_ in directory.
Read-Host "There are no files prepended with _7Y_ in this directory!"
}
if ($directoryInfo.count -eq 0){ #Check: No files in directory.
Read-Host "There are no files in this directory!"
}
}
【问题讨论】:
-
由于您将文件移动到子目录,因此移动当然是可逆的,没有任何问题。
标签: powershell file-management