如何实现,当出现问题时,就终止,而不会继续进行下一条语句呢?


PowerShell交流中心分类: 变量-函数-脚本-条件-循环-参数如何实现,当出现问题时,就终止,而不会继续进行下一条语句呢?
0
Elijah0221 asked 7 年 ago

我有这样一个script,请问,如何实现,当出现问题时,就终止,而不会继续进行下一条语句呢?
param(
[string]$Action,
[string]$ServerList,
[string]$ResourcePath,
[string]$TargetPath,
[string]$File
)
$servers = Get-Content $ServerList
foreach ($server in $servers)
{
 #Get the new file content
 $content = Get-Content $ResourcePath\$File -Raw
 
 #Generate te targert folder path
 $remoteFilePath = “\\{0}\{1}” -f $server,$TargetPath
 Write-Host “Start to backup the orignal file: $remoteFilePath\$File”
 
 Rename-Item -path $remoteFilePath\$File -newname Backup_$File
 Write-Host “Start to replace the file to: $remoteFilePath\$File”
 
 $content| Out-File $remoteFilePath\$File -Force
}
根据上面的设置,在rename的时候,如果Backup_$File存在的话,会出错,但是,系统还是会继续下面的替换操作,导致原有的文件丢失。
请各位大神,帮忙完善,使得更加人性化。谢谢。。。

1 Answers
1
Best Answer
Mooser Lee 管理员 answered 7 年 ago
 Rename-Item -Path .\a.html .\json.txt.txt -ErrorAction SilentlyContinue
 if($?)
 {
 Write-Host '重命名成功,继续执行'
 }
 else
 {
 Write-Warning $Error[0].Exception.Message
 Write-Warning '重命名失败,结束执行!'

 }