Powershell Get-Content loads in a previous version of a file that has been modified

Jairo Javier Baleta Cali 131 Reputation points
2024-05-08T16:31:13.0966667+00:00

I have a problem with the Get-Content command since it often loads an older version of the file it is reading. When this happens, you have to run the Get-Content command several times to update it to load the latest version of the file. I have searched and found nothing so far about this incident.

I hope you can help me.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,418 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,185 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 49,251 Reputation points
    2024-05-08T17:02:49.3066667+00:00

    This isn't possible. Get-Content literally just calls the underlying provider for the path you give it. For the file system provider it is probably calling the File.ReadAllText method which is just a wrapper around the underlying Win32 file operation. There is no concept of "previous versions" built into any of this.

    It sounds to me like you have a timing issue here. However you haven't shared any details on when this file gets updated, what the "previous version" means and what your script is doing. Off the top of my head some things that come to mind:

    • You're trying to read a file that is on a distributed file system or perhaps OneDrive and so the version you're reading is a cached copy that hasn't been updated yet. PS has no control over this.
    • You're using the File History feature of NTFS and something isn't right about it. PS has no control here either.
    • You are writing the file at the same time you're trying to read it so depending upon how the file is being written determines when you'd see the updated file contents.
    • Your script is programmatically figuring out the file to load and it is loading the wrong file.

    There are other possibilities but without an understanding of what your script does it would be hard to guess.