Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2406
  • Last Modified:

Get-Content File Locked test?

I have a powershell script which every 30 seconds tries to read teh content of an output file. The output file is the result of running a script like this:
C:\scripts\myscript.ps1 > C:\temp\outputfile.txt

The problem I am running into is that occasionally (randomly) the Get-Content command files due to the file being locked.

How can I test that the file is not locked prior to my Get-Content command?
A function would be easiest, so that I could:
If (Test $filename) { get-content ... }

Thoughts?
0
rwskas
Asked:
rwskas
  • 2
  • 2
1 Solution
 
soostibiCommented:
I would do this:

$content = Get-Content C:\yourlockedfile.txt -ErrorAction silentlycontinue
if($?){"Success"}else{"faliure"}
0
 
rwskasAuthor Commented:
Yeah, Thats how I have it setup now.. I would prefer to check it prior to trying to get the content though, because I dont really want to turn on EA silentlycontinue as I would still like to review other error messages.
0
 
soostibiCommented:
In the failure part you can check end emit the error by reading the $error[0] variable.
0
 
rwskasAuthor Commented:
Your solution works, its just not what I was asking..
0

Featured Post

Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now