如何解决在移动文件之前寻求 Powershell 功能以检查是否存在多个文件夹
背景故事:在将更新安装到 NAS 上的单个文件夹之前,我备份了我的 Android 应用程序。我想使用映射到此文件夹的 Windows 机器每天(如果不是每周)运行一个 powershell 脚本,我知道该怎么做。
目标:是将文件按部分名称(例如:Adobe Acrobat * 和 Adobe Scan *)移动到使用公司名称预定义的文件夹结构中,然后在该文件夹中放入产品. (例如:\Adobe\Acrobat\ & \Adobe\Scan)
到目前为止我有:
$Adobe = "Z:\APK\Adobe\" #Set Path For Adobe Folder
#Adobe Products
If (!(test-path $Adobe)) #Check if Adobe Folder Does Not Exist
{
#If Does Not Exist Create Folder
New-Item -ItemType Directory -Force -Path $Adobe
}
#Move Anything matching "Adobe" in its name to the $Adobe folder
Move-Item Z:\Adobe* $Adobe -Force
问题:
-
正如您在我的代码中看到的,我将 Adobe* 的所有内容都放入了 Adobe 文件夹,但无法弄清楚如何使用空格从上述示例中获取产品名称。
-
必须有一种比为每个文件夹编写测试路径更简单的方法,因为有 100 多个应用程序,我通常希望存储更多来自家人和朋友的应用程序,以便您了解这些应用程序将如何增长。所以我希望有一个函数来检查循环中的所有文件夹,如果它们不存在,则创建该结构。为方便起见,我们可以使用上面两个 Adobe 产品的示例。
免责声明:如果我发布代码,它将在 Github 上开源,并且我的脚本中内置了 Credits,但我打算将其用于个人用途和 0 商业收益
解决方法
我可能会做这样的事情
$path = 'C:\temp\powershell\apk_organizer\apk'
$apkFiles = Get-ChildItem -Path $path -Filter *.apk -File
$apkFiles | ForEach-Object {
# Get vendor and product strings
$vendor,$product,$null = $_.BaseName -split ' '
# Generate the new path
$newPath = [System.IO.Path]::Combine($path,$vendor,$product)
# or
# $newPath = Join-Path $path (Join-Path $vendor $product)
# Create new path if it does not exist
if (!(Test-Path $newPath)){
New-Item -ItemType Directory -Path $newPath | Out-Null
}
# Move file to new path (Remove -WhatIf after testing)
Move-Item $_ -Destination $newPath -Verbose -WhatIf
}
,
为了让球滚动以便其他人也可以发表评论,我会踢它。希望我理解你是对的,所以请耐心等待。假设我们在位置 A 中拥有您尝试移动的所有这些应用程序。假设应用程序名称按产品 ( Adobe
) 和版本 ( Acrobat
) 我们可以采用按产品和版本拆分名称的方法。
$Where_My_Apps_Are = "E:\My\Apps\Location"
$Where_I_want_Them_To_Be = "D:\My\Apps\Destination"
$My_Apps = Get-ChildItem -Path $Where_My_Apps_Are -Filter "Adobe*" -File -Recurse
foreach ($App in $My_Apps) {
$Name_Split = $App.BaseName.Split(' ')
$App_NameFolder = Join-Path -Path $Where_I_want_Them_To_Be -ChildPath $Name_Split[0]
$App_Version = Join-Path -Path $App_NameFolder -ChildPath $Name_Split[1]
$App_Name_Test = Test-Path -Path $App_NameFolder
$App_Version_Test = Test-Path -Path $App_Version
if ($App_Name_Test -eq $false) {
New-Item $App_NameFolder -ItemType Directory
if ($App_Version_Test -eq $false) {
New-Item $App_Version -ItemType Directory
Move-Item $App.FullName -Destination $App_Version
}
else {
Move-Item $App.FullName -Destination $App_Version
}
}
elseif ($App_Version_Test -eq $false) {
New-Item $App_Version_Test -ItemType Directory
Move-Item $App.FullName -Destination $App_Version
}
else {
Move-Item $App.FullName -Destination $App_Version
}
}
看,这个问题是我假设所有应用程序都是产品,然后版本格式用空格分隔。我们可以将所有相关应用收集到一个变量 ( $My_Apps
)、拆分名称、针对名称的每个部分进行测试、如果不存在则创建一个文件夹、将项目移动到目录中,或者只是移动项目 (app ) 进入目录(如果目录存在)。
如果你把它变成一个函数并传递一个过滤变量来搜索特定的应用程序,只是为了方便手动移动,那可能是最好的,但你也可以让它为它找到的所有应用程序做这件事; 假设它们都采用上述格式。
请注意:只是想为读者指出正确的方向(如果我理解正确),以便他们可以给你一个更好的答案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。