【问题标题】:Powershell copy file failed if file missing如果文件丢失,Powershell 复制文件失败
【发布时间】:2016-02-29 20:59:23
【问题描述】:

我想将 file1、file2、file3、file4 和 file5 中的数据附加到 finalfile。

所以副本是

Copy-Item $file1 $finalfile
add-content -path $finalfile-value (get-content $file2)
add-content -path $finalfile-value (get-content $file3)
add-content -path $finalfile-value (get-content $file4)
add-content -path $finalfile-value (get-content $file5)

但是如果文件没有退出就会报错,所以如果部分文件丢失,如何重写代码,例如file2丢失,脚本仍然会继续为file3添加内容。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    为什么不尝试这样的事情呢?

    if(Test-Path $file2){ add-content -path $finalfile -value (get-content $file2)}
    

    Test-Path 将测试它是否可以找到目录/文件并返回真/假。如果找到该文件,if 语句将执行 add-content 命令。如果找不到文件,则 if 什么也不做

    【讨论】:

      【解决方案2】:

      使用 try catch 或设置 $ErrorActionPreference 变量来处理您的错误。

      【讨论】:

      • 在每个 add-content 语句的末尾添加 -ErrorAction SilentlyContinue
      猜你喜欢
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多