Powershell 抓取额外文件

Powershell grabbing extra files

我有这个 Powershell 代码:

Function CheckFileList()
{
    $limit = (Get-Date).AddDays(-270)
    $input_path = gci '//blah/folder/' | sort -property LastWriteTime
    $output_file = 'c:\PowershellScripts\prune_results.txt'
    #Clear-Content $output_file
    $countf = 0
    $outputstr = ""

    $outputstr = $(Get-Date -format 'F') + " - Folders to be purged:`r`n"

    $input_path | Foreach-Object{
        if ( (Get-Item $_.FullName) -is [System.IO.DirectoryInfo] ) {
            if ( $_.LastWriteTime -le $limit ) {
                $source=$input_path + $_.Name
                $dest="\server\otherfolder" + $_.Name
                $what=@("/MOVE")
                $options=@("/COPY:DAT /DCOPY:T")
                $cmdArgs = @("$source","$dest",$what,$options)
                "robocopy " + $cmdArgs >> $output_file
                #robocopy @cmdArgs
                #Move-Item $_.FullName \server\otherfolder
                $outputstr = $outputstr + " (" + $_.LastWriteTime + ") `t" + $_.Name + "`r`n"
                $countf++
                $outputstr = $outputstr + "Folders [to be] purged: " + $countf + "`r`n`r`n"
                $outputstr >> $output_file
                Exit
            }
        }
    }

    #$outputstr = $outputstr + "Folders [to be] purged: " + $countf + "`r`n`r`n"
    #$outputstr >> $output_file

}

CheckFilelist

此代码仅用于显示命令的执行方式运行。它只有1个循环(第一个循环后退出),所以它应该抓取1个文件夹。

但输出量很大,似乎包括所有文件夹 (1000+) 而不是一个。它是这样的:

robocopy file1.txt FOLDER1 FOLDER2 FOLDER3 FOLDER4 ........ \server\otherfolder\FOLDER5

我是不是漏掉了什么?它应该将 //blah/folder/ 上的文件夹移动到不同的网络文件夹 (\server\otherfolder)

您问题的核心在于您的填充方式$source

$source=$input_path + $_.Name

这是因为你如何定义 $input_path

$input_path = gci '//blah/folder/' | sort -property LastWriteTime

你在所有项目中循环,而实际上只寻找一个。还有其他方法可以得出相同的结论。 $input_path 不是路径,而是“//blah/folder”中文件夹和文件的集合

$input_path = gci 'c:\temp' | Where-Object{($_.LastWriteTime -le $limit) -and ($_.PSIsContainer)}
$input_path | ForEach-Object{
    #... do things
    $_.FullName
    # Fullname is the complete path. 
}

关于 Robocopy

如果您查看 robocopy 文档中的 /MINAGE,我认为大部分逻辑都可以变得多余

/MINAGE:n Excludes files with a Last Modified Date newer than n days or specified date. If n is less than 1900, then n is expressed in days. Otherwise, n is a date expressed as YYYYMMDD.

尽管在阅读了您的评论并再次提出问题后,这很可能不是您要找的东西。

关于Move-Item

我看到你也在尝试这样做。使用我们的新 $input_path 管道传输到 Move-Item 应该可以正常工作。如果您需要日志记录,您可以使用 ForEach-Object 以允许在其他地方记录额外信息。

$input_path | Move-Item -Destination "\server\otherfolder"