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

问题描述 投票:0回答:1

以下命令在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
    }
powershell
1个回答
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 ...

}
© www.soinside.com 2019 - 2024. All rights reserved.