powershell - 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")
解决方案
我不确定我是否正确理解了您的问题。以下脚本将遍历特定目录中的所有 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
推荐阅读
- debugging - 发送大节时,Ejabberd 会变慢
- c# - C# 无法将类转换为 IEnumerable
- excel - Vba Shell 调用适用于某些程序,但不适用于其他程序
- openstreetmap - 即使在 OpenStreetMaps 中的非英语国家,是否仍然无法为所有国家使用英文名称
- flutter - TextFormField 向后输入值 [Flutter]
- java - java xslt 转换本地名称
- excel - 下标与上标冲突
- google-apps-script - 必须反复授权
- asp.net - 我在 Action Method 上使用了 Authorize 属性,我是否需要检查用户是否经过身份验证?
- amazon-web-services - AWS MediaConvert:转码后删除原始文件