Home > other >  Error on Move-Item moving home area to file server
Error on Move-Item moving home area to file server

Time:10-16

This is the last section of my script that I use to transfer student leavers areas to an archive file server. The script runs and does everything as expected but still throws an error out saying Move-Item : Cannot find path '\\domain\students$\E-J$\MH201507' because it does not exist. The script does find this path and moves the home area so I'm not sure why I get this error. Or is there any way to fix this or is it easier to hide the error somehow?

The CSV document contains a list of the sam account name and contains their home area location on the domain so it knows where to copy the path over from.

Any help would be massively appreicaited! Kind Regards

#Declaring the .csv file that contains a list of all leavers home directories.

$HomeDirectoryList = Import-CSV "C:\Scripts\Leavers\HomeDirectoryExport.csv"

$Username = $HomeDirectoryList.samAccountName

$HomeDirectory = $HomeDirectoryList.HomeDirectory

$Archive = "\\myfileserver.ac.uk\D$\21-22 Leavers"

ForEach ($Username in $HomeDirectoryList)
{
    Move-Item -Path $HomeDirectory -Destination $Archive
}

Sample data with which the error occurs:

samAccountName  HomeDirectory
WB214589    \\domain\students$\A-D$\WB214589
MH201507    \\domain\students$\E-J$\MH201507

CodePudding user response:

You are setting the variable $HomeDirectory outside the loop, so that will contain an array of home directory paths.

Then you use variable $Username to iterate the data from the CSV file, but inside that loop you never use it.

Try:

$HomeDirectoryList = Import-CSV 'C:\Scripts\Leavers\HomeDirectoryExport.csv'
$Archive           = '\\myfileserver.ac.uk\D$\21-22 Leavers'

foreach ($student in $HomeDirectoryList) {
    Write-Host "Moving HomeDirectory folder for student '$($student.samAccountName)'"
    Move-Item -Path $student.HomeDirectory -Destination $Archive -Force
}

If you need to catch errors happening, change the loop to:

foreach ($student in $HomeDirectoryList) {
    Write-Host "Moving HomeDirectory folder for student '$($student.samAccountName)'"
    try {
        Move-Item -Path $student.HomeDirectory -Destination $Archive -Force -ErrorAction Stop
    }
    catch {
        Write-Warning "Error moving homedirectory '$($student.HomeDirectory)':`r`n$($_.Exception.Message)"
    }
}
  • Related