Powershell比较如果语句不起作用

时间:2018-09-18 15:05:51

标签: powershell

我正在编写PowerShell脚本,该脚本将查看txt文件$file_list,然后将该文件中的文件名与/bin目录中的文件进行比较。

如果它们匹配,则它将将该文件移动到指定的文件夹$destination_folder

问题是if语句未执行-它会尝试将所有文​​件从/bin移到$destination_folder

$file_list = Get-Content "C:\files\Patching\Worker\list.txt"
$search_folder = “C:\Program Files\NetBrain\Worker Server\bin”
$destination_folder = “C:\files\Patching\Backups”


foreach ($item in $file_list) {
  $file_to_move = Get-ChildItem -Path $search_folder -Filter $file -Recurse -ErrorAction SilentlyContinue -Force | % { $_.FullName}
  $destination_folder = “C:\files\Patching\Backups”

  if ($file_to_move.name -like $item) {
    Move-Item $file_to_move $destination_folder
  }
}

1 个答案:

答案 0 :(得分:0)

我找到了解决方法。我没有通过Get-ChildItem调用正确解析。要解决此问题,需要使用嵌套的foreach{}

$file_list = Get-Content "C:\files\Patching\Worker\list.txt"
$bin_folder = "C:\Program Files\NetBrain\Worker Server\bin"
$backups_folder = "C:\files\Patching\Backups"

#Move files from bin to backup
foreach ($item in $file_list) {

 foreach ($file in Get-ChildItem $bin_folder) {

   if ($file -like $item) {
      $file_to_move = "C:\Program Files\NetBrain\Worker Server\bin\$file"
      Move-Item $file_to_move $backups_folder
      Add-Content $output_file "$file_to_move"
   }
}

}