简体   繁体   中英

Powershell Set-Content empty file on error

I have some script to modify hosts . It's something like this:

@echo off

Powershell.exe -NoProfile  -Command "& { $var = cat c:\...\hosts; 
                                         $var =  $var -replace '....','....'
                                         try { 
                                           Set-Content c:\...\hosts $var -ErrorAction Stop 
                                         } catch { 
                                           echo 'CAN`T WRITE'; pause; exit 2; 
                                         }
                                       }"

exit $LASTEXITCODE

This is only an example, real script is more complex.

The problem is that sometimes script shows CAN'T WRITE error, but hosts file becomes empty, all the content is gone. Any suggestions on how i can prevent losing file content on Set-Content error?

When you execute a statement in Try block, it is actually executed. Then if $var is $null, then the text file gets empty. And you see the error message using Catch block. Then you can save the content before, and if error occurs return the original file back in the Catch block:

@echo off

Powershell.exe -NoProfile  -Command "& { $var = cat c:\...\hosts;
                                         $oldvar = $var 
                                         $var =  $var -replace '....','....'
                                         try { 
                                           Set-Content c:\...\hosts $var -ErrorAction Stop 
                                         } catch { 
                                           echo 'CAN`T WRITE'; pause; exit 2;
                                           $oldvar | Set-Content C:\...\hosts
                                           New-Item "Backup.txt" -Type File -Value $oldvar
                                         }
                                       }"

exit $LASTEXITCODE

$oldvar will contain the the original content of the text file which can you use later. And to be more safe, i have added to write the content into a backup file (Backup.txt) if Writing again to the file fails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM