【问题标题】:Powershell Copy item from Array to ArrayPowershell 将项目从数组复制到数组
【发布时间】:2016-01-15 16:05:52
【问题描述】:

我想将DateTime 格式的文件夹复制到名为Weekday 的文件夹中。文件夹 D:\TEST\2015-06-23T2300+0000 应复制到 D:\TEST\Thursday。

Get-ChildItem $Path | Select FullName
D:\TEST\2015-06-23T2300+0000                                                                            
D:\TEST\2016-01-07T2300+0000                          

Get-ChildItem $Path | ForEach {$_.LastWriteTime.DayOfWeek}
Thursday
Friday

这是我现在有的代码,但它不起作用。我错过了一些东西。

$Path = "D:\TEST"
$source = Get-ChildItem $Path | Select FullName
$dest = Get-ChildItem $Path | ForEach {$_.LastWriteTime.DayOfWeek}
  foreach ($source in $sources)
    {
    Copy-Item -Path $source -Destination "D:\TEST2\$dest" -Recurse
    }

欢迎任何帮助。

【问题讨论】:

  • “不工作”是什么意思?究竟会发生什么?你有任何错误吗?
  • 在您的示例中,$dest 成为一个字符串数组,其中包含 all 您所有文件的可能工作日 - Copy-Item -Destination 无法“猜测”哪个属于每个文件文件
  • 什么都没有发生,只需要脚本。没有输出,也没有复制文件。

标签: powershell dayofweek get-childitem copy-item


【解决方案1】:

您正在使用所有可能的工作日值填充$dest

在查看并复制时,按项目检索工作日:

$Sources = Get-ChildItem $Path
foreach($Source in $Sources)
{
    $Weekday = $Source.LastWriteTime.DayOfWeek
    $Destination = "D:\Test\$Weekday"

    Copy-Item $Source.FullName -Destination $Destination -Recurse    
}

【讨论】:

  • 工作就像一个魅力。谢谢。
  • 必须更改 Copy-Item $Source.FullName -Destination $Destination\$Source -Recurse 以维护 Weekday 文件夹中的文件夹结构。
【解决方案2】:

试试这个代码, 它工作正常,我已经测试过:

$Dir = "c:\files"
$Items = Get-ChildItem -Path $Dir
foreach ($Item in $Items)
{
    if (!($Item -is [System.IO.DirectoryInfo]))
    {
        Copy-Item -Path $Item.FullName -Destination .\Desktop\$($Item.LastAccessTime.DayOfWeek)
    }
}
  • 这个目录 c:\files 应该有一个子目录用于一周中的每一天。

【讨论】:

    猜你喜欢
    • 2020-12-23
    • 2021-11-03
    • 2014-07-26
    • 2011-05-08
    • 2022-01-12
    • 2014-09-05
    • 1970-01-01
    相关资源
    最近更新 更多