首页 > 解决方案 > 移动项目不移动文件

问题描述

我尝试使用 powershell 重命名 csv,然后在没有文件时将其自动移动到另一个文件夹。最初,csv 名称如下所示:import_9999_2020-08-13_132238.csv但带有 9999 的部分也可以仅包含 2 或 3 位数字。我的实际代码如下所示:

#Import of path and target-path
$path = "\\network-path\subfolder\subfolder\subfolder\subfolder\subfolder1\"
$target_path =  "\\network-path\subfolder\subfolder\subfolder\subfolder\subfolder2\"


#endless loop
$a=$true
while($a -eq $true){
    $Files = gci $path
    $TargetFiles = gci $target_path
    
    #wait 5 minutes if path is empty
    if(($Files).Count -eq 0){
        sleep -Seconds 300
    }

    #if path is filled with one or more files
    else {
        #if file in target-path is processed (from another program)
        if(($TargetFiles).count -eq 0){
            #rename and move the latest file
            get-childitem -path $path -Filter "import_*.csv"|
                where-object { -not $_.PSIsContainer } | 
                sort-object -Property $_.CreationTime | 
                select-object -last 1 |
                Rename-Item -NewName {($_.Name.Substring(0,($_.Name.Length)-22))+".csv"} |
                Move-Item -Destination $target_path +"$($_.Name).csv"
        }
         sleep -Seconds 20
    }
}

它部分工作并重命名 csv,但不会将其移动到目标路径。路径是正确的,我已经从 Windows-Explorer 中复制了它。任何想法,为什么该程序不能完全运行?谢谢

标签: powershell

解决方案


如果要将其传递到管道中,请添加-PassthruRename-Itemcmdlet

Somefile.txt | Rename-Item -NewName {$_.basename + "abc" + $_.ext} | # nothing in the pipeline

Somefile.txt | Rename-Item -NewName {$_.basename + "abc" + $_.ext} -Passthru | # now the new named fileinfo object is in the pipeline, contained in automatic variable $_ 

推荐阅读