首页 > 解决方案 > foreach (#file in $files){ nul find "2019" $file save(D:\Export2019\$file) }

问题描述

.ps1 如果文件中有特定文本,则将文件复制到特定位置

我正在尝试 Powershell 中的代码...我在 S:\Export\ 中有很多 .xml 文件,我想复制文件夹 S:\Export2019\ 中包含文本“2019”的文件

这是我的代码:

Start-Transcript -Path S:\Export2019\info.txt
$files = Get-ChildItem "S:\Export\"
mkdir S:\Export2019
foreach ($file in $files){
>nul find "<APPDATE>2019" $file (
  echo $file was found.
  Save("S:\Export2019\$file")
) 
}
ii S:\Export2019 #

我在 S:\Export\ 中有很多 .xml 文件,我想复制文件夹 S:\Export2019\ 中包含文本“2019”的文件

这不起作用:

>nul find "<APPDATE>2019" $file (
  echo $file was found.
  Save("S:\Export2019\$file")

标签: powershell

解决方案


我不确定我是否正确理解了您的问题。以下脚本将遍历特定目录中的所有 XML 文件并搜索 text 2019。如果该文本在文件中,它将被复制到另一个目录中

请注意,此脚本是一种非常粗糙且“蛮力”的方法,但它应该为您提供使用的基础

$source_dir = ".\S_Export2019" # Directory where the XML files are
$target_dir = ".\Target_Directory" # Directory where "2019" files will be copied to

# Loop through the directory $source_dir and get the fullpath of all XML-files
foreach ($file in (Get-ChildItem "$source_dir\*.xml")) {
    # Save the content of the XML file
    $file_content = Get-Content $file -raw

    # Check if the XML file contains "2019"
    if ($file_content -match "2019") {
        Write-Host "$file contains '2019'"
        Copy-Item $file $target_dir # Copy file to $target_dir
    }
}

编辑 感谢@LotPings 的更正-我已将-raw参数添加到,Get-Content并将if-comparison 更改为使用-match而不是前者-contains


推荐阅读