为什么递归在if语句中不起作用?

时间:2020-08-21 08:56:16

标签: powershell

我正在尝试编写脚本,以将扩展名为.txt的文件的内容复制到一个。脚本正在运行,但-recurse无法运行。 (它不复制子文件夹中的文件),我也不知道为什么。这是我的脚本的样子:

function UnifyConfigs {
        param (
        $destination = "C:\temp\all.txt",
        [Parameter()]
        $files
    )
  
    foreach ($config in $files) {
        If((Get-ChildItem $config -Recurse).LastWriteTime -gt (Get-Item $destination).LastWriteTime)
        {
            Clear-Content -path $destination
            Set-Content -path $destination -value (Get-Content $config) 
        }
        else {
            break
        }  
    }
}

是的:我已经使用-force进行过尝试:-)

1 个答案:

答案 0 :(得分:1)

首先,您需要将Get-ChildItem -Recurse调用移至将输入字符串解析为文件系统中实际文件的位置:

foreach ($config in Get-ChildItem $files -Recurse) {
    if($config.LastWriteTime -gt (Get-Item $destination).LastWriteTime)
    {
        Clear-Content -path $destination
        Set-Content -path $destination -value (Get-Content $config) 
    }
    else {
        break
    }  
}

如果您只想测试输入文件中的 any 是否比目标文件新,然后用其他txt文件的 all 覆盖目标的内容,这实际上变得有点简单-我们可以完全放弃外部循环:

# Discover all the files
$configFiles = Get-ChildItem $files -Recurse

# use `-gt` and the destination timestamp to "filter" all the config file timestamps
# if _any_ of them are newer that $destination, then the condition is true
if(@($configFiles.LastWriteTime) -gt (Get-Item $destination).LastWriteTime){
    # pipe every file to Get-Content, and then overwrite $destination with the whole thing
    $configFiles |Get-Content |Set-Content -Path $destination -Force
}

我还建议重构参数名称,以更好地反映预期的输入(“ C:\ path \ to * files”是代表“ path”的字符串,而不是“ files”):

function Update-UnifiedConfig {
    param (
        [Parameter(Mandatory = $false)]
        [string]$DestinationPath = "C:\temp\all.txt",

        [Parameter(Mandatory = $true)]
        [string]$Path
    )

    $destinationLastModified = (Get-Item -LiteralPath $DestinationPath).LastWriteTime

  $configFiles = Get-ChildItem $files -Recurse

  if(@($configFiles.LastWriteTime) -gt $destinationLastModified){
    $configFiles |Get-Content |Set-Content -LiteralPath $DestinationPath -Force
  }
}

我在上面大多数地方使用-LiteralPath的原因是因为$DestinationPath就是这样,-Path另一方面会将通配符视为 expandable 仅适用于此函数中的$Path参数值