I am writing PowerShell script that will look at txt file $file_list
and then compare filename within that file to files within a /bin
directory.
If they match it will then move that file to a specified folder $destination_folder
.
The issue is that the if
statement is not executing - it will attempt to move all the files from the /bin
to $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
}
}
I found the fix. I was not parsing through the Get-ChildItem call properly. To correct this a nested foreach{}
is needed.
$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"
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.