从CSV移动并重命名-子字符串并加入

时间:2018-10-29 08:22:45

标签: powershell csv

我正在尝试移动和重命名CSV文件中的循环。 我看过其他线程并尝试实现,但是不断得到:

You cannot call a method on a null-valued expression.
At C:\Temp\test dir\dirtemp\oldkmove.ps1:6 char:6
+      $char = ($_.old).Substring(0, 1)

我知道此错误是指子字符串组件,但我敢肯定还有其他问题。

我想将.\B.RVG\B000003的文件夹移动到.\1689

代码:

$path = ".\"

Import-Csv -Delimiter "," -Path "C:\Temp\test dir\dirtemp\olddirmove.csv" | foreach {
    $char = ($_.old).Substring(0, 1)
    $rvg =  $char + ".RVG"
    $fromdir = $rvg + "\" + $_.old
    $topath = Join-Path $path -ChildPath $_.new
    $frompath = Join-Path $path -ChildPath $fromdir

    Move-Item $frompath -Destination $topath
}

CSV:

old,    new  
B000003,    1689  
...

此后,我已经更新了代码,但是当我运行它时,它不会继续运行并停在此检查中缺少的第一个文件夹中:

编辑:用“返回”替换“继续”可解决此问题。


#If File does not exist then skip.
If (!(Test-Path $frompath)) {
    Write-Verbose "File $($frompath) Does not exist, skipping"
    Continue
}

有什么建议吗? 此外,我应该开始一个新的话题,还是在这里添加一个正确的东西?

谢谢


    #initialisation
    CLS
    $ErrorActionPreference = "continue"
    $VerbosePreference = "continue"

    #Settings
    Start-Transcript -Path C:\temp\PSTranscript.txt -Append


     $path = ".\"
    $FileListFile = ".\FINALEXPORT.csv"


    #Try to moving the files from the list to the the specified subfolder.
    Import-Csv -Delimiter "," -Path "C:\Temp\FINALEXPORT.csv" | foreach {

         $char = ($_.EXTNUM).substring(0,1)
        $rvg =  $char + ".RVG"
        $fromdir = $rvg + "\" + $_.EXTNUM
        $topath = Join-Path $path -ChildPath $_.matched_key
        $frompath = join-path $path -ChildPath $fromdir


        #If File does not exist then skip.
        If (!(Test-Path $frompath)) {
            Write-Verbose "File $($frompath) Does not exist, skipping"
            Continue
        }

        # Check if files already exist in the sub folder.
        If (Test-Path ($topath)){
            Write-Verbose "File $($_.matched_pat_sys_id) exists already in the subfolder, skipping"
            Continue    
        }


        #try copying the file.
        Try {
            $frompath | Move-Item -Destination $topath;
            Write-Verbose "File $($fromdir) succesfully moved."

        }
        Catch {Write-Warning "Could not move file $($fromdir), Skipping"} 

    }


    Write-Verbose "Script finished." #, waiting for 5 seconds before closing."
    start-sleep
    Stop-Transcript

0 个答案:

没有答案