if/else 声明和复制项目问题
if/else statement and copy-item issue
这里是简单的脚本,至少我认为它应该是这样,但我对最终结果有疑问:
$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"
}
}
}
问题是它从不复制文件,我哪里出错了?
提前感谢您的帮助。
除了打印到屏幕外,Write-Host
不会向管道发送任何内容,因此 Copy-Item
不会收到任何要复制的内容。
只需在 Write-Host
之后调用 Copy-Item
而不是在前者中传递后者:
$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"
}
}
}
另请查看格式和命名。
这里是简单的脚本,至少我认为它应该是这样,但我对最终结果有疑问:
$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"
}
}
}
问题是它从不复制文件,我哪里出错了?
提前感谢您的帮助。
除了打印到屏幕外,Write-Host
不会向管道发送任何内容,因此 Copy-Item
不会收到任何要复制的内容。
只需在 Write-Host
之后调用 Copy-Item
而不是在前者中传递后者:
$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"
}
}
}
另请查看格式和命名。