gpt4 book ai didi

PowerShell:try-catch 不起作用

转载 作者:行者123 更新时间:2023-12-02 23:12:35 26 4
gpt4 key购买 nike

我有一个 PowerShell 脚本,它从文件中获取文件名列表,在文件夹中搜索文件名,将它们存档,然后执行其他操作。

#make non-terminating errors behave like terminating errors (at script level)
$ErrorActionPreference = "Stop"

#set the folder that has the list and the files
$some_path = "D:\some_folder\"
$archive = "D:\archive\"

#set the list file name
$file_list = $some_path + "file_list.txt"

#get the files that I'm searching for from this list file
$files_to_retrieve = Select String -Path $file_list -Pattern "something" | Select-Object Line

#get the number of files for this search string
$n = $file_list.Length - 1

#seed the while loop counter
$i = 0

#while loop to archive and modify the files
While ($i -le $n)
{
#set the current file name
$current_file = $path + $files_to_retrieve[$i].Line

try
{
Copy-Item -Path $current_file -Destination $archive_path
}
catch
{
Write-Host ("file " + $files_to_retrieve[$i].Line + " not found")
}

$data = Get-Content $current_file

#do modifications here
}

try-catch 未按预期工作。我的文件列表中有一个文件名不存在于 $some_path 中。我期待 try-catch 停止执行并执行 Write-Host。相反,它不会运行 Write-Host 并继续执行 $data = Get-Content $current_file 步骤,该步骤会引发终止错误,因为缺少文件的路径不存在。我该如何解决这个问题?

最佳答案

正如您所知,您的第一个问题是 try/catch 。简单看一下documentation for about_Try_Catch_Finally你会看到的..

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

您的 Copy-Item 行不会引发终止错误。我们使用通用参数 -ErrorAction

修复该问题
Copy-Item -Path $current_file -Destination $archive_path -ErrorAction Stop

因此,如果出现问题,则应调用 Catch block 。假设那是真正的问题。


我认为您还有另一个问题,这可能只是一个拼写错误。我不止一次看到以下代码片段。

$file_list[$i].Line

之前您已将 $file_list 声明为“D:\some_folder\file_list.txt”,它是一个字符串。我想你想要的在下面。上面的代码将为空,因为字符串没有行属性。但是 Select-String 的返回可以!

$files_to_retrieve[$i].Line

关于PowerShell:try-catch 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33456028/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com