此问题是按预期工作的较大脚本的一部分。
问题是,如果缺少其中一个文件夹,脚本将失败。
我尝试了不同的if
语句,但这超出了我的了解。
2个问题:
这是脚本:
Param (
[parameter(Mandatory=$false)]
[String[]]$IncludeFolders = @("Desktop", "Documents", "Pictures", "Videos", "Favorites")
)
#$IncludeFolders
foreach ($IncludeFolder in $IncludeFolders) {
& psexec ("\\" + $ServerUsersHome) -s -u $ServerUsersHomeUsername -p $ServerUsersHomePassword -w $ServerUsersHomeTempPath robocopy ($ServerUsersHomeFromPath + "\" + $IncludeFolder) ($ServerUsersHomeToPath + "\" + $IncludeFolder) $IncludeFiles /S /COPY:DAT /DCOPY:T /R:2 /W:5 /V /TEE ("/LOG+:" + $robocopylogfilename)
Write-Log ("Remote executed robocopy completed. Exit code " + $LastExitCode) 5
} #IncludeFolders
答案 0 :(得分:2)
Q1:在代码中执行此操作会使命令行非常混乱,甚至不值得尝试。考虑使用Invoke-Command
在远程主机上运行循环,并使用Test-Path
检查路径是否存在。
$pw = ConvertTo-SecureString $ServerUsersHomePassword -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential $ServerUsersHomeUsername, $pw
Invoke-Command -Computer $ServerUsersHome -ScriptBlock {
Set-Location $using:ServerUsersHomeTempPath
foreach ($IncludeFolder in $using:IncludeFolders) {
$src = "${using:ServerUsersHomeFromPath}\${IncludeFolder}"
if (Test-Path $src -Container) {
& robocopy $src $using:IncludeFiles /S /COPY:DAT /DCOPY:T /R:2 /W:5 /V /TEE "/LOG+:${using:robocopylogfilename}"
}
}
} -Credential $cred
第二季度:在上述代码中的else
语句中添加一个if
分支,您将信息写入到另一个文件中。
if (Test-Path $src -Container) {
robocopy ...
} else {
"Missing folder: ${src}" | Add-Content 'C:\path\to\missing_folders.log'
}