I'm trying some more advanced PowerShell scripts lately, one of my colleagues asked me to make something that moves the 16 first created files from one folder to the next unless it is not empty. I got it checking and making a list of those 16 files but I can't get it to move them to the specific folder.
Here is the code so far:
$OriginPath = "D:\test\files"
$DestinationPath = "D:\test\test"
$MoveNr = "16"
$MoveFiles = ""
$LogFile = "D:\test\files\Move-Log.log"
$TimeStamp = Get-Date -Format "dd-MM-yyyy_hh-mm-ss"
# Check if Destination folder is empty.
if ((Get-ChildItem $DestinationPath -Filter *.uni | Measure-Object).Count -eq 0) {
# Folder is Empty
echo 'Moved ' $TimeStamp >> $LogFile
Write-Warning "Files are moving, one moment"
$MoveFiles = Get-ChildItem $OriginPath -Filter *.uni |
Sort -Property LastWriteTime |
Select -First $MoveNr |
Out-File $LogFile
ForEach-Object $MoveFiles | Move-Item -Path $OriginPath -Destination $DestinationPath >> $LogFile
} else {
# Folder is not empty
Write-Warning "Folder not empty!"
}
Write-Warning "Now back to work!"
It runs everything without errors but moves nothing, nor does it write in the logfile like it is supposed to, the list does get inserted tho.
The problem is occurring because you have used | Out-File
on the end of the line that generates the collection of files in to $MoveFiles
. Because Out-File
creates no object output, that variable doesn't get populated.
Do this instead:
$MoveFiles = Get-ChildItem $OriginPath -Filter *.uni |
Sort -Property LastWriteTime |
Select -First $MoveNr
$MoveFiles | Out-File $LogFile
You also probably don't need ForEach-Object
on the line after this (and your use of it is invalid), nor should you declare -Path
in Move-Item
, because that is coming from the pipeline. E.g:
$MoveFiles | Move-Item -Destination $DestinationPath
Should work.
The >> $LogFile
here might be redundant as Move-Item
doesn't generate any output.