powershell : command does not work when called inside a loop

0

The following command does work in a powershell console

Restore-SvnRepository D:\temp\Backup\foo.vsvnbak

(Restore-SvnRepository is a command that comes with visualsvn, it expects a path or unc to a file to be restored as parameter)

As I need to execute this command for a large number of files (>500) I embedded it inside a powershell loop but then it doesn't work

$fileDirectory = "D:\temp\Backup"
$files = Get-ChildItem $fileDirectory -Filter "*.vsvnbak"

foreach($file in Get-ChildItem $fileDirectory)
{
    $filePath = $fileDirectory + "\" + $file;

    # escape string for spaces
    $fichier =  $('"' + $filepath + '"')    

    # write progress status
    "processing file " + $fichier 

    # command call
    Restore-SvnRepository $fichier
}

Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

I don't understand why this does not work. The loop and filename looks good but when executed, each command throws the following error message

Restore-SvnRepository : Parameter 'BackupPath' should be an absolute or UNC path to the repository
backup file you would like to restore: Invalid method Parameter(s) (0x8004102F)

Could you help me?

EDIT

It looks like that I was confused by Get-ChildItem that return a System.IO.FileSystemInfo rather than a string.
I didn't notice because of a implicit call to the ToString() when writing to the console that made me think I was dealing with string (rather than FSI)

The following code works

$fileDirectory = "D:\temp\Backup\"
$files = Get-ChildItem $fileDirectory -Filter "*.vsvnbak"

    foreach($file in $files) 
    {
        # $file is an instance of System.IO.FileSystemInfo, 
        # which contains a FullName property that provides the full path to the file. 
        $filePath = $file.FullName

         Restore-SvnRepository -BackupPath $filePath
    }
powershell
asked on Stack Overflow Sep 10, 2018 by frenchone • edited Sep 10, 2018 by frenchone

1 Answer

5

$file isn't a string, it's an object containing file data.

You can simplify your code as follows:

$fileDirectory = "D:\temp\Backup"
$files = Get-ChildItem $fileDirectory -Filter "*.vsvnbak"

foreach($file in $files) 
{
    # $file is an instance of System.IO.FileSystemInfo, 
    # which contains a FullName property that provides the full path to the file. 
    $filePath = $file.FullName 

    # ... your code here ...

}
answered on Stack Overflow Sep 10, 2018 by Daniel Mann

User contributions licensed under CC BY-SA 3.0