2

If I read file that another process is occupied using Get-content, then working well. But, read the file by [IO.File]::ReadAllText and display error message: The file is occupied by another process.

mklement0
  • 382,024
  • 64
  • 607
  • 775
user11230064
  • 63
  • 1
  • 6
  • 2
    Are you saying that the two methods do not act the same when trying to read from a file currently locked by another process? That would be unexpected - please update your question with a [mcve]. By contrast, the methods differ in what other processes are allowed to do with a file while these methods have a given file open - see https://stackoverflow.com/a/51619034/45375. – mklement0 Mar 20 '19 at 08:04

1 Answers1

4

Here is the basic concept between the two.

# returns array of lines in the file
Get-Content "FileName.txt"

# returns one string for whole file.
[System.IO.File]::ReadAllText("FileName.txt")

# There are ways to achieve second behavior with Get-Content, as of PowerShellv3 and later

Get-Content "FileName.txt" -Raw

# in PowerShell 2:
Get-Content "FileName.txt" | Out-String

Details are in the MS docs.

File.​Read​All​Text Method

Get-Content (Microsoft.PowerShell.Management)

You can view the source code of Get-Content on the MS PowerShell GitHub page. If you really want to see what is under the covers, or you can use Trace-Command to see the steps taken when you use them in code.

postanote
  • 15,138
  • 2
  • 14
  • 25
  • 2
    Good general information, but - despite the question's generic title - it is not what the OP is asking for. To complete the general information, I suggest pointing out the pitfall with using relative paths with .NET methods (different working directories). Also, as an alternative to piping to `Out-String` in v2 , `(Get-Content "FileName.txt") -join [Environment]::NewLine` avoids a trailing newline in the resulting string. – mklement0 Mar 20 '19 at 08:13