robocopy在创建文件夹时添加隐藏的符号

如何解决robocopy在创建文件夹时添加隐藏的符号

我要做的是使用powershell ps1文件和Windows PowerShell ISE将照片文件从SD卡复制到HDD。 我从图像exif获取拍摄日期并将其添加到目标路径。 问题是robocopy会创建文件夹并添加奇怪的前缀,这是我不想拥有的。 结果,我可以看到两个具有相同名称“ 2020”的子文件夹,一个是手动创建的文件夹,另一个是由robocopy创建的文件夹。 仅当我列出带有CMD的文件夹时,才会看到此前缀。 在output.log和powershell中看不到该前缀。

enter image description here

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 stringscustom format specifiers

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-