从 powershell v5 中的替换方法捕获异常
Catch Exception from replace method in powershell v5
我正在尝试编写脚本来查找和替换文件中的字符串。如果脚本由于某种原因无法替换字符串并将其记录在外部文件中,我该如何捕获异常?这是我目前所拥有的。
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-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 语句,首先测试字符串是否存在于文件中,然后跳过替换并检查它是否存在。