Move-item 2 issues

I am trying to move certain files from c:\ on a list of servers to a central location. I have 2 problems.

  1. Apparently I don’t have access to all of them (and I’m not sure which ones). I tried to use write-output but couldn’t get the server name.
  2. Some of the files are still being written to and are locked. (ideally I would just skip those. I tried to use try / catch but couldn’t get the syntax to work. Here is my code:
$file = import-csv -LiteralPath "F:\auditFilesFromLocalServers\auditserverList.csv" 

foreach($i in $file)
{
         If (-not (Move-Item -Path "\\$($i.name)\c`$\auditLogs\*.sqlaudit" -Destination "\\myCentralServer\F`$\auditFilesFromLocalServers" ))
         {
    Throw "Folder Access Denied"  # and this causes NONE of the servers to transfer files. 
         }
}

The files need to be processed be each to track what happens for each file. The following is not tested, but should be fairly close:

$csv = import-csv -LiteralPath "F:\auditFilesFromLocalServers\auditserverList.csv" 

$results = foreach($row in $csv) {
    $source = '\\{0}\c$\auditLogs\*.sqlaudit' -f $row.Name    
    $destination = '\\myCentralServer\F`$\auditFilesFromLocalServers'
    
    $files = Get-ChildItem -Path $source
    
    foreach ($file in $files) {
        try {
            Move-Item -Path $file.FullName -Destination $destination -ErrorAction Stop 
            [PSCustomObject]@{
                ComputerName = $row.Name
                SourcePath   = $source
                Source       = $file.FullName
                Destination  = $destination
                Status       = 'SUCCESS'
            }
        }
        catch {
            [PSCustomObject]@{
                ComputerName = $row.Name
                SourcePath   = $source
                Source       = $file.FullName
                Destination  = $destination
                Status       = 'FAILED: {0}' -f $_
            }        
        }
    }
}

Rob’s code removing some redundant parts. Still not tested

$csv = import-csv -LiteralPath "F:\auditFilesFromLocalServers\auditserverList.csv" 

$results = foreach($row in $csv) {
    $source = '\\{0}\c$\auditLogs\*.sqlaudit' -f $row.Name    
    $destination = '\\myCentralServer\F`$\auditFilesFromLocalServers'
    
    $files = Get-ChildItem -Path $source
    
    foreach ($file in $files) {

        try {
            Move-Item -Path $file.FullName -Destination $destination -ErrorAction Stop 
            $status = 'SUCCESS'
        }
        catch {
            $status = 'FAILED: {0}' -f $_
        }

        [PSCustomObject]@{
            ComputerName = $row.Name
            SourcePath   = $source
            Source       = $file.FullName
            Destination  = $destination
            Status       = $status
        } 
    }
}
1 Like