Home > OS >  Move Item path null
Move Item path null

Time:08-03

I have to move files from a folder corresponding to a CSV column like that :

id name
1a file1
2b file2
3c file3
4d file4

So if in my folder I have a file named file1 I need to create a folder named 1a and put file1 inside.

I have the following script

$CsvId = Import-Csv './test.csv'
$sourcePath= "C:\Users\olong\Desktop\object"
$dirPath = "C:\Users\olong\Desktop\dir"
$files = Get-ChildItem -Path $sourcePath | ForEach-Object -Process {[System.IO.Path]::GetFileNameWithoutExtension($_)}
$pattern = '(?<=_).*(?=_)'  

ForEach ($item In $CsvId) {
   $objectID = $item.'id'
   $docID = $item.'name'  
   $location = $dirPath  "\"   $objectID

  Foreach ($file in $files) {
       
    if($file -contains $docID) {
      if (-not (Test-Path -Path $location)) {
        mkdir -Path $location
    }

    Move-Item ($file.FullName) -Destination $location -Verbose -Force

}
}
}

But it gives me that error :

Move-Item : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\olong\Desktop\scriptMove.ps1:19 char:15
      Move-Item ($file.FullName) -Destination $location -Verbose -Force
                ~~~~~~~~~~~~~~~~
      CategoryInfo          : InvalidData: (:) [Move-Item], ParameterBindingValidationException
      FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.MoveItemCommand

With PowerShell's debugger $file is not null and with or without parenthesis on $file.FullName does nothing

CodePudding user response:

I think what you want to do is to get the file(s) as mentioned in the csv under header 'name' having any extension into a subfolder as mentioned in field 'id' and create that subfolder first if it does not already exist.

If my assumtion is correct, you can try below:

$sourcePath      = "C:\Users\olong\Desktop\object"
$destinationPath = "C:\Users\olong\Desktop\dir"

Import-Csv -Path './test.csv' | ForEach-Object {
    $targetDirectory = Join-Path -Path $destinationPath -ChildPath $_.id
    # create the output subfolder if it does not already exist
    $null = New-Item -Path $targetDirectory -ItemType Directory -Force
    # next use the file basename from the $_.name column as filter and move the file(s)
    Get-ChildItem -Path $sourcePath -Filter "$($_.name).*" -File | Move-Item -Destination $targetDirectory
}
  • Related