如何解决robocopy在创建文件夹时添加隐藏的符号
我要做的是使用powershell ps1文件和Windows PowerShell ISE将照片文件从SD卡复制到HDD。 我从图像exif获取拍摄日期并将其添加到目标路径。 问题是robocopy会创建文件夹并添加奇怪的前缀,这是我不想拥有的。 结果,我可以看到两个具有相同名称“ 2020”的子文件夹,一个是手动创建的文件夹,另一个是由robocopy创建的文件夹。 仅当我列出带有CMD的文件夹时,才会看到此前缀。 在output.log和powershell中看不到该前缀。
this.filterSelectDataSource.next(someNewObject);
如果写$copy_from = "G:\DCIM\100MSDCF\"
$copy_to = "C:\Photos\"
function GetDateTaken {
param (
[Parameter(ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true)]
[Alias('FullName')]
[String]
$Path
)
begin {
$shell = New-Object -COMObject Shell.Application
}
process {
$returnvalue = 1 | Select-Object -Property Name,DateTaken,Folder
$returnvalue.Name = Split-Path $path -Leaf
$returnvalue.Folder = Split-Path $path
$shellfolder = $shell.Namespace($returnvalue.Folder)
$shellfile = $shellfolder.ParseName($returnvalue.Name)
$returnvalue.DateTaken = $shellfolder.GetDetailsOf($shellfile,12)
$returnvalue.DateTaken
}
}
$file = Get-ChildItem -Path $copy_from -recurse -include ('*.jpg','*.arw')
$i = 0
$jpg = 0
$arw = 0
$logifile = 'output.log'
if ([System.IO.File]::Exists($logifile)) {
Clear-Content $logifile
Write-Host ("Logfile cleaned: $logifile")
} else {
try {
New-Item -Path . -Name $logifile | Out-Null
Write-Host ("New logfile created: $logifile")
}
catch {
"Failed to create $logifile"
}
}
foreach ($file in $file) {
if ($file.extension -eq '.JPG') { $jpg++ }
if ($file.extension -eq '.ARW') { $arw++ }
$i++
$datetaken = ($file.fullname | GetDateTaken).Split(' ')[0]
$datetaken_Day = $datetaken.Split('.')[0]
$datetaken_Month = $datetaken.Split('.')[1]
$datetaken_Year = $datetaken.Split('.')[2]
$TargetPath = "$copy_to$datetaken_Year\$datetaken_Month\$datetaken_Day\"
Write-Host ("$i. " + $file.Name + " `tDate taken: " + $datetaken)
robocopy $copy_from $TargetPath $file.Name /ts /fp /v /np /unilog+:$logifile | Out-Null
}
Write-Host ("`nTotal: " + $i + " files (" + $jpg + " JPG files," + $arw + " ARW files)")
,则无济于事。
如果我将$TargetPath = $copy_to + $datetaken_Year + "\" + $datetaken_Month + "\" + $datetaken_Day + "\"
选项设置为robocopy,则无济于事。
但是,例如,当我手动设置年份时,一切正常/fat
创建正确的文件夹名称应该解决什么?
解决方法
使用COM对象中的GetDetailsOf()
方法返回本地化的结果,这将导致您的荷兰计算机上的函数以'dd-MM-yyyy HH:mm'格式返回日期(周围带有不可见的字符)
一种更好的IMO方法是使用System.Drawing.Imaging.Metafile
获取以空终止的字节数组形式读取exif数据的日期,并使用以下函数将其中的日期解析为DateTime对象:
function Get-ExifDate {
# returns the 'DateTimeOriginal' property from the Exif metadata in an image file if possible
[CmdletBinding(DefaultParameterSetName = 'ByName')]
Param (
[Parameter(Mandatory = $true,ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true,Position = 0,ParameterSetName = 'ByName')]
[Alias('FullName','FileName')]
[ValidateScript({ Test-Path -Path $_ -PathType Leaf})]
[string]$Path,[Parameter(Mandatory = $true,ParameterSetName = 'ByObject')]
[System.IO.FileInfo]$FileObject
)
Begin {
Add-Type -AssemblyName 'System.Drawing'
}
Process {
# the function received a path,not a file object
if ($PSCmdlet.ParameterSetName -eq 'ByName') {
$FileObject = Get-Item -Path $Path -Force -ErrorAction SilentlyContinue
}
# Parameters for FileStream: Open/Read/SequentialScan
$streamArgs = @(
$FileObject.FullName
[System.IO.FileMode]::Open
[System.IO.FileAccess]::Read
[System.IO.FileShare]::Read
1024,# Buffer size
[System.IO.FileOptions]::SequentialScan
)
try {
$stream = New-Object System.IO.FileStream -ArgumentList $streamArgs
$metaData = [System.Drawing.Imaging.Metafile]::FromStream($stream)
# get the 'DateTimeOriginal' property (ID = 36867) from the metadata
# Tag Dec TagId Hex TagName Writable Group Notes
# ------- --------- ------- -------- ----- -----
# 36867 0x9003 DateTimeOriginal string ExifIFD (date/time when original image was taken)
# get the date taken as an array of bytes
$exifDateBytes = $metaData.GetPropertyItem(36867).Value
# transform to string,but beware that this string is Null terminated,so cut off the trailing 0 character
$exifDateString = [System.Text.Encoding]::ASCII.GetString($exifDateBytes).TrimEnd("`0")
# return the parsed date
return [datetime]::ParseExact($exifDateString,"yyyy:MM:dd HH:mm:ss",$null)
}
catch{
Write-Warning -Message "Could not read Exif data from '$($FileObject.FullName)'"
}
finally {
If ($metaData) {$metaData.Dispose()}
If ($stream) {$stream.Close()}
}
}
}
另一种选择是下载并解压缩ExifTool
(您可以从here下载zip文件)
然后像这样使用它:
$exifTool = 'Path\To\Unzipped\ExifTool.exe' # don't forget to 'Unblock' after downloading
$file = 'Path\To\The\ImageFile' # fullname
# retrieve all date tags in the file
# -s2 (or -s -s) return short tag name add the colon directly after that
$allDates = & $exifTool -time:all -s2 $file
# try to find a line with tag 'DateTimeOriginal','CreateDate' or 'ModifyDate'
# which will show a date format of 'yyyy:MM:dd HH:mm:ss'
# and parse a DateTime object out of this string
$dateTaken = switch -Regex ($allDates) {
'^(?:DateTimeOriginal|CreateDate|ModifyDate):\s(\d{4}:\d{2}:\d{2} \d{2}:\d{2}:\d{2})' {
[datetime]::ParseExact($matches[1],'yyyy:MM:dd HH:mm:ss',$null)
break
}
}
以上内容返回的简短说明
这两个方法均返回将图像作为DateTime 对象而不是字符串的日期。
该对象具有.Year
,.Month
,.Day
等属性。它还具有.AddDays()
,.ToShortDateString()
,.ToString()
等各种方法更多。
如果您按照注释执行$datetaken = ($datetaken -split ' ')[0]
,则要求PowerShell使用默认 ToString()方法将隐式转换为字符串。 br />
如果您愿意,可以在代码中使用该ToString()方法,只要您在括号之间提供所需的格式字符串。
例如,如果您执行$dateTaken.ToString('yyyy\\MM\\dd')
,则如果$ dateTaken是今天,则您将得到一个字符串2020\10\08
,该字符串可以用作文件路径的一部分。
在您的代码中,您可以执行以下操作:
$TargetPath = Join-Path -Path $copy_to -ChildPath $dateTaken.ToString('yyyy\\MM\\dd')
# if that path does not exist yet,create it
if (!(Test-Path -Path $TargetPath -PathType Container)) {
$null = New-Item -Path $TargetPath -ItemType Directory
}
然后继续,然后将文件复制到现有的$ TargetPath
请查看您可以在DateTime对象上使用的所有standard format strings和custom format specifiers。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。