关于Powershell:Powershell-如何根据文件的最后修改日期创建目录?

Powershell - how to create directories based on last modify date of files?

我是PS的新手。我已经找到了扫描目录(或递归目录)并获取文件的最后修改日期属性的脚本,但是我无法基于该日期创建目录。我要完成的工作是这样的:

日期-----------文件

2012-01-03 Fax1.mfs

2012-01-04 Fax2.mfs

2012-01-04 Fax3.mfs

创建以下目录:

2012-01-03

2012年1月4日

有了这个,我们可以使用另一个脚本根据文件的最后修改日期来移动文件。

这是我到目前为止创建的:

1
Get-ChildItem -Path C:\\temp\\path | Foreach {$_.LastWriteTime.tostring("MM-dd-yyyy")}

哪个以字符串格式MM-dd-yyyy给出日期。我只需要将它作为变量传递给

1
| % {New-Item -Name ($_).tostring("MMddyyyy") -ItemType directory}

这会出错,并且不会创建任何目录。

任何帮助将不胜感激。


基本处于疯狂汤姆叶片相同,但拉LastWriteTime作为一个单独的管线阶段,并明确的属性值调用的newitem。不够简洁,但可以说更具可读性。

1
2
3
4
5
6
7
8
9
10
$p ="h:\\temp\\240214"

get-childitem -Path $p |
    Select-Object -ExpandProperty LastWriteTime |
        foreach-object {
            New-Item -Path $p
                -Name $_.ToString("yyyy-MM-dd")
                -ItemType Directory
                -ErrorAction SilentlyContinue
            }

要解决将文件移动到适当文件夹中的后续问题...

1
2
3
4
5
6
7
8
9
10
11
$p ="h:\\temp\\240214"

get-childitem -Path $p |
    Where-Object { ! ($_.PSIsContainer) } |
    ForEach-Object {
        $newDir = join-path $p ($_.LastWriteTime).ToString("yyyy-MM-dd")
        New-Item -Path $newDir  `
            -ItemType Directory `
            -ErrorAction SilentlyContinue
        $_ | Move-Item -Destination $newDir
    }


这样的事情如何:

1
2
$Path = 'C:\\temp\\path'
Get-ChildItem $Path | Foreach-Object {mkdir"$Path\\$($_.LastWriteTime.ToString('MM-dd-yyyy'))" -ErrorAction SilentlyContinue}