Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@Howlaind Howlaind commented May 22, 2020

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

@TTTPOB

This comment has been minimized.

Copy link
Owner Author

@TTTPOB TTTPOB commented May 22, 2020

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

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

@Howlaind

This comment has been minimized.

Copy link

@Howlaind Howlaind commented May 23, 2020

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

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

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

This comment has been minimized.

Copy link
Owner Author

@TTTPOB 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