Powershell single line file exists check

enthuguy used Ask the Experts™
Hi Powershell experts,

please help me in the logic. Below is the current single line script.

foreach($line in Get-Content C:\filepath.txt){(Get-Content $line).replace('DB_URL', ${RDSInstance.Endpoint.Address}) ^| Set-Content $line}

Open in new window

Would like extend a bit by
  1. check if file exists, then apply replace logic,
  2. else get next line
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Test-Path is your friend:
foreach ($line in Get-Content C:\filepath.txt) {If (Test-Path -Path $line) {(Get-Content $line).replace('DB_URL', ${RDSInstance.Endpoint.Address}) ^| Set-Content $line}}

Open in new window

Haven't tested this but it should work:

$FileCheck = "c:\filepath.txt"; if (!test-path $filecheck){Exit}else {try{foreach($line in Get-Content C:\filepath.txt){(Get-Content $line).replace('DB_URL', ${RDSInstance.Endpoint.Address}) ^| Set-Content $line}}catch {write-host "Something Went Wrong Processing line $($line)"}}

Open in new window

oBdA has the better solution..


Thanks a lot oBdA, ITguy,
will test these :)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial