powershell:在循环内调用时,命令不起作用

时间:2018-09-10 13:48:27

标签: powershell

以下命令在Powershell控制台中确实有效

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

(Restore-SvnRepository是visualsvn附带的命令,它期望将文件的路径或unc作为参数恢复)

因为我需要对大量文件(> 500)执行此命令,所以我将其嵌入到powershell循环中,但是它不起作用

$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');

我不明白为什么这行不通。循环和文件名看起来不错,但是在执行时,每个命令都会引发以下错误消息

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)

你能帮我吗?

编辑

看起来我对Get-ChildItem感到困惑,因为它返回System.IO.FileSystemInfo而不是字符串。
我没有注意到,因为在写入控制台时隐式调用ToString(),使我认为我正在处理字符串(而不是FSI)

以下代码有效

$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
    }

1 个答案:

答案 0 :(得分:5)

$file不是字符串,而是包含文件数据的对象。

您可以按如下方式简化代码:

$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 ...

}