首页 > 解决方案 > 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)

你可以帮帮我吗?

编辑

看起来我对返回 System.IO.FileSystemInfo 而不是字符串的 Get-ChildItem 感到困惑。
我没有注意到,因为在写入控制台时对 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
    }

标签: powershell

解决方案


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

}

推荐阅读