来自powershell v5中的replace方法的Catch Exception

时间:2017-04-13 21:26:23

标签: powershell powershell-v5.0

我正在尝试编写一个脚本来查找和替换文件中的字符串。如果脚本由于某种原因无法替换字符串并将其记录在外部文件中,如何捕获异常?这是我到目前为止所拥有的。

Write-Host "Checking Execution Policy"

$currentExecutionPolicy = Get-ExecutionPolicy
    if( $currentExecutionPolicy -eq "RemoteSigned")
        {
            Write-Host "Execution policy check passed"
        } 
    else 
        {
            "Setting Execution policy to RemoteSigned as per https://msdn.microsoft.com/powershell/reference/5.1/Microsoft.PowerShell.Core/about/about_Execution_Policies"
            Set-ExecutionPolicy Remotesigned
        }

Write-Host "Starting Script"

#Recurse through all the file shares and find the file.
$rootPath='\\do.main.name\shared\Information Technology\IT\u.name'
    $hotspotFile = Get-ChildItem -Path $rootPath -Recurse -Include "hotspot.mac" 
     Write-Host "Found file" $hotspotFile
     $logstring = "Found file" + $hotspotFile
     WriteLog $logstring

       try
       {
         (Get-Content $hotspotFile).Replace("olddomain.com","do.main.name") | Set-Content $hotspotFile    

       }
       catch
       {

        Write-Host "Failed to replace string -" $file
        $logstring = "Failed to replace string -" + $file
        WriteLog $logstring
       }


#Logging
$Logfile = "F:\u.name\Documents\Logs\SCR_To_Find_And_Replace_Old_Domain_String.log"

Function WriteLog
{
   Param ([string]$logstring)

   Add-content $Logfile -value $logstring
}

1 个答案:

答案 0 :(得分:1)

根据评论,我认为失败的替换不会产生异常,因此您无法使用try catch。

相反,您可以使用if测试,例如:

If ($hotspotfile -notcontains "do.main.name") { }

或者测试文件是否存在旧字符串。如果字符串首先出现在文件中并跳过替换并检查它是否为“

”,那么你也可以明智地在早期的if语句中测试它。