抑制文件夹不存在



这个问题是按预期工作的更大脚本的一部分。问题是,如果其中一个文件夹丢失,脚本将失败。我尝试过不同的if语句,但这超出了我的知识范围。

2个问题:

  1. 如何抑制脚本中丢失的文件夹,使其不会失败
  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

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

Q2:在上面代码中的if语句中添加一个else分支,将信息写入另一个文件。

if (Test-Path $src -Container) {
robocopy ...
} else {
"Missing folder: ${src}" | Add-Content 'C:pathtomissing_folders.log'
}

相关内容

最新更新