Forum Discussion
Powershell keeps file open Out-file -append / Add-content
Hi AkitoTheGambler,
you can address this file locking issue by using the .NET System.IO.File methods for writing to the file. Replace all occurrences of Out-File -FilePath $logFile -Append with [System.IO.File]::AppendAllText($logFile, $yourMessage).
For instance, instead of:
Write-Output $certMessage | Out-File -FilePath $logFile -Append
You can try:
[System.IO.File]::AppendAllText($logFile, $certMessage)
Please click Mark as Best Response & Like if my post helped you to solve your issue.
This will help others to find the correct solution easily. It also closes the item.
If the post was useful in other ways, please consider giving it Like.
Kindest regards,
Leon Pavesic
(LinkedIn)
unfortunately we are using ConstrainedLanguage mode so we cannot use it
but running out-file manually doesnt usually lock the file after running
but somehow in some cases in scriptblocks or functions it does.
i dont understand why tho. (but not always, idk what the conditions are that cause it to behave like this)
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_language_modes?view=powershell-5.1#constrainedlanguage-mode
- AkitoTheGamblerNov 27, 2023Copper Contributor
i was trying to figure out why this happens as it only breaks inside the Scriptblock but doesnt hangup and keep it open if its everything outside the scriptblock
so
Write-Output $certMessage | Out-File -FilePath $logFile -Append Write-Output $timestampMessage | Out-File -FilePath $logFile -Append
always works finebut everything inside the foreach scriptblock fails
- guinoronhaApr 15, 2024Copper ContributorHi AkitoTheGambler,
Did you find a solution for this? I have the same issue. I use a function to write data to a log file and I get "random" access denied errors when writing to the file.