if / else语句和copy-item问题

时间:2017-02-13 20:00:38

标签: powershell shortest-path copy-item write-host

这里的简单脚本,至少我认为它应该是,但我遇到了最终结果的问题:

$a = Get-Content "content\file\location"
$destfile = "destination\of\file"
$source ="source\file\location"
$dest = "c$\destination"
$destfolder = "c:\folder\destination"

foreach ($a in $a) {
    if (Test-Connection $a -Count 1 -Quiet) {
        if (Test-Path "\\$a\$destfile") {
            Write-Host $a "File exists" -ForegroundColor Green
        } else {
            Write-Host $a "File is missing and will now be copied to $a\$destfolder" -ForegroundColor Red |
                Copy-Item $source -Destination "\\$a\$dest"
        }
    }
}

问题是它永远不会复制文件,我哪里出错?

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

除了打印到屏幕外,Write-Host不会向管道发送任何内容,因此Copy-Item不会收到任何要复制的内容。

只需在Copy-Item之后调用Write-Host,而不是在后者中使用后者:

$computerList = Get-Content "content\file\location"
$destfile = "destination\of\file"
$source ="source\file\location"
$dest = "c$\destination"
$destfolder = "c:\folder\destination"

foreach ($computerName in $computerList) {
    if (Test-Connection $computerName -Count 1 -Quiet) {
        if (Test-Path "\\$computerName\$destfile") {
            Write-Host $computerName "File exists" -ForegroundColor Green
        } else {
            Write-Host $computerName "File is missing and will now be copied to $computerName\$destfolder" -ForegroundColor Red
            Copy-Item $source -Destination "\\$computerName\$dest"
        }
    }
}

请同时查看格式和命名。