从powershell v5中的替换方法捕获异常

从powershell v5中的替换方法捕获异常,powershell,powershell-5.0,Powershell,Powershell 5.0,我正在尝试编写一个脚本来查找和替换文件中的字符串。如果脚本由于某种原因无法替换字符串并将其记录到外部文件中,如何捕获异常?这是我到目前为止所拥有的 Write-Host "Checking Execution Policy" $currentExecutionPolicy = Get-ExecutionPolicy if( $currentExecutionPolicy -eq "RemoteSigned") { Write-Host "Exec

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

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
}

根据评论,我认为失败的替换不会生成异常,因此不能使用try-catch

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

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

或者测试文件是否存在旧字符串。您可能会明智地加入一个更早的if语句,首先测试字符串是否存在于文件中,然后跳过替换并检查它是否存在。

此脚本在哪些方面不符合您的期望?此外,您最好使用Write Verbose而不是Write Host。对不起,我可能应该在问题中提到。当它实际上在该文件中找不到字符串时,它无法抛出错误。找不到要替换的字符串不是例外。脚本需要测试字符串是否在文件中。Replace()没有出错地完成了它的工作。它将“a”改为“b”。仅仅因为“a”没有被替换并不代表失败。