【问题标题】:PowerShell - sort&move files by Edit datePowerShell - 按编辑日期排序和移动文件
【发布时间】:2021-06-14 13:57:11
【问题描述】:

简单的任务。但无法意识到。 我只需要从一个目录 (x) 获取文件并移动到另一个 (z) + 创建名为“YYYY”的文件夹(上次编辑的年份),然后创建名为“MM”的子文件夹(上次编辑的月份)。

所以我找到了脚本并尝试根据我的需要调整它。但是,我无法成功运行它。 这是我以女巫为例:

$files= Get-ChildItem -File «C:\Files\»
foreach ($file in $files) {
if ($file.lastwritetime -lt $lastweek) {
$file | Move-Item -Force -Destination { md («C:\Files\» + $_.LastWriteTime.ToString(«yyyy.MM») + «\» + $_.LastWriteTime.ToString(«yyyy.MM.dd»)) -Force}
}
}

所以我根据它制作了我的:

 $files=  Get-childitem -path "c:\Files"
$files | foreach-object {Move-Item -Force -Destination { md ("C:\Files\" + $_.LastWriteTime.ToString("yyyy")+"\"+$_.LastWriteTime.ToString("MM"))}} 

请帮我完成它! 我不是很擅长 powershell...

【问题讨论】:

  • 我们还没有收到您的来信.. 作为 SO 新手您可能不知道这一点,但习惯上点击左侧的 图标 accept the answer that best solved your problem .这将帮助其他有类似问题的人更轻松地找到它,并有助于激发人们回答您的问题。

标签: powershell sorting subdirectory


【解决方案1】:

最好不要通过将字符串与+ 连接来构造路径。为避免错误,请为此使用Join-Path cmdlet。

另外我建议不要试图在一行代码中塞那么多,因为当它失败时,真的很难调试。

试试

$path = 'C:\Files'
Get-childitem -Path $path -File | 
    ForEach-Object {
        $destination = Join-Path -Path $path -ChildPath ('{0}\{1:D2}' -f $_.LastWriteTime.Year, $_.LastWriteTime.Month)
        $null = New-Item -Path $destination -ItemType Directory -Force
        $_ | Move-Item -Destination $destination
    }

你可以像这样创建目标路径来缩短代码:$destination = Join-Path -Path $path -ChildPath ('{0:yyyy\\MM}' -f $_.LastWriteTime),但是你必须记住通过加倍来转义-f格式模板字符串中的反斜杠

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2016-04-01
    • 1970-01-01
    • 2019-07-25
    相关资源
    最近更新 更多