PowerShell: try-catch not working

前端 未结 1 1130
我寻月下人不归
我寻月下人不归 2020-12-20 04:46

I have a PowerShell script that gets a list of file names from a file, searches a folder for the file names, archives them, and then does other stuff.

#make          


        
相关标签:
1条回答
  • 2020-12-20 04:54

    Your first problem is the try/catch as you know. Taking a brief look at the documentation for about_Try_Catch_Finally you will see that..

    Use Try, Catch, and Finally blocks to respond to or handle terminating errors in scripts.

    Your Copy-Item line is not throwing a terminating error. We fix that with the common parameter -ErrorAction

    Copy-Item -Path $current_file -Destination $archive_path -ErrorAction Stop
    

    So if there is a problem then the Catch block should be called. Assuming that was the real issue there.


    You have another issue I think as well that might just be a typo. I see the following snippet more than once.

    $file_list[$i].Line
    

    Earlier you have declared $file_list as "D:\some_folder\file_list.txt" which is a string. I think what you meant to have is below. The above code would be null since string dont have a line property. But the return from Select-String can!

    $files_to_retrieve[$i].Line
    
    0 讨论(0)
提交回复
热议问题