【问题标题】:Powershell Compare-Object on empty folder空文件夹上的 Powershell 比较对象
【发布时间】:2012-11-22 10:51:39
【问题描述】:

我正在编写一个简单的 DLL 复制脚本来帮助我的开发团队设置他们的本地环境。我检查了构建 devdrop 文件夹并获得了 DLL 文件列表。然后我查看本地文件夹并复制任何较新的 DLL。

我的问题是当本地文件夹为空时(即脚本第一次运行时)它会崩溃。

$newFiles = Get-ChildItem -recurse -path "$drop\$latest\ship" -name
$oldFiles = Get-ChildItem -recurse -path $bin -name

$files = Compare-Object $newFiles $oldFiles -IncludeEqual -PassThru
$files | Where-Object { $_.SideIndicator -eq '<=' -or $_.SideIndicator -eq '=='} | % {
    Copy-Item -Path "$drop\$latest\ship\$_" -Destination $bin -Force
}

当 $bin 为空时,gci 调用将 $oldFiles 保留为 null,给我一个很好的错误:

Compare-Object : 无法将参数绑定到参数“DifferenceObject”,因为它为空。

我已经四处搜索,所有比较对象的操作方法似乎都没有处理这个问题。我可以检查文件夹是否为空,然后将所有文件复制过来,但我想知道是否有更好的方法。

干杯。

【问题讨论】:

  • 检查文件夹是否为空有什么问题?这只是额外的一行代码。
  • 主要是因为我想使用Compare-Object的SideIndicator。稍后在脚本中,我需要识别本地文件夹中不再提供的 DLL(即检查 =>)。希望这个问题可以帮助将来想做类似事情的人。

标签: powershell scripting


【解决方案1】:
$newFiles = @(Get-ChildItem -recurse -path "$drop\$latest\ship" -name)
$oldFiles = @(Get-ChildItem -recurse -path $bin -name)
$files = Compare-Object -ReferenceObject $newFiles -DifferenceObject $oldFiles -IncludeEqual -PassThru

【讨论】:

  • 这么简单,没想到这么简单。
  • +1。在某个时候,我写了一页同步脚本。这本可以为我节省一些时间。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
  • 2019-04-21
  • 2021-11-09
  • 2022-01-19
相关资源
最近更新 更多