Skip to content

Instantly share code, notes, and snippets.

@TTTPOB
Last active August 7, 2020 06:42
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save TTTPOB/20859243237c1ba751aee24baf27b689 to your computer and use it in GitHub Desktop.
Save TTTPOB/20859243237c1ba751aee24baf27b689 to your computer and use it in GitHub Desktop.
OneDrive photo auto backup on phone will put all your photo in one place, I wrote this powershell script to sort them into different folders. It is easy to read and modify.
Get-ChildItem . | Foreach-Object -Process {
$subPath = $_.LastWriteTime.year.tostring() + "\" + $_.LastWriteTime.year.tostring() + "." + $_.LastWriteTime.month.tostring("00")
$from = $_.Name
function Move-Android ($subdest) {
Write-Output $_.Name
$dest = $subdest + "\" + $subPath
if (!(Test-Path $dest)) {
New-Item -Path $dest -ItemType Directory | Out-Null
}
move-item $from $dest
}
function Move-iOS ($subdest, $prefix, $suffix) {
Write-Output $_.Name
$realModifiedTime = $_.LastWriteTime.ToString("yyyyMMdd_HHmmss")
$newName="$($prefix)_$($realModifiedTime)$($suffix)"
$dest = "$($subdest)\$($subPath)"
Rename-Item -Path $_ -NewName $newName
Write-Output $dest
if (!(Test-Path $dest)) {
New-Item -Path $dest -ItemType Directory | Out-Null
}
Move-Item -Path $newName -Destination $dest
}
switch -regex -casesensitive ($_) {
"^VID" {
Move-Android("Video")
Break
}
"^IMG|^PANO" {
Move-Android("Photo")
Break
}
"^WIN" {
Move-Android("Photo")
}
"^Screen" {
Move-Android("Screenshot")
Break
}
"iOS.heic$" {
Move-iOS "Photo" "IMG" ".heic"
Break
}
"iOS.png$" {
Move-iOS "Screenshot" "Screenshot" ".png"
Break
}
"iOS.jpg$" {
Move-iOS "Saved" "Saved" ".jpg"
Break
}
"iOS.MOV$" {
Move-iOS "Video" "VID" ".MOV"
Break
}
default {}
}
}
@Howlaind
Copy link

第二行用 $subPath=$_.LastWriteTime.ToString("yyyy\\yyyy.MM") 应该就可以了

@TTTPOB
Copy link
Author

TTTPOB commented May 22, 2020

第二行用 $subPath=$_.LastWriteTime.ToString("yyyy\\yyyy.MM") 应该就可以了

我这还是第一次用powershell,没想到可以这么优雅,谢谢啦

@Howlaind
Copy link

我这还是第一次用powershell,没想到可以这么优雅,谢谢啦

客气了
如果不嫌我多嘴,我再啰嗦两句😂
整个代码还可以更优雅些的

  • 正则本来就可以匹配后方有更多字符的情况,所以 Pattern 后面不用加 .*
  • Switch 语句里重复语句太多,可以写在函数里,然后调用函数。函数的语法可以参考官方文档里的 about_functions

@TTTPOB
Copy link
Author

TTTPOB commented May 23, 2020

我这还是第一次用powershell,没想到可以这么优雅,谢谢啦

客气了
如果不嫌我多嘴,我再啰嗦两句😂
整个代码还可以更优雅些的

  • 正则本来就可以匹配后方有更多字符的情况,所以 Pattern 后面不用加 .*
  • Switch 语句里重复语句太多,可以写在函数里,然后调用函数。函数的语法可以参考官方文档里的 about_functions

谢谢啦一会改~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment