简体   繁体   中英

powershell write to file

I've written a GUI for making changes in AD and I need every action logged. This GUI is used by multiple users at once and writes to one file but only first person that writes to the log file can actually write to it. Everyone else has access denied. I'm using streamwriter like this.

$File = "$LogPath\$LogDate.log"
$stream = [System.IO.StreamWriter] $File
$stream.WriteLine("----------------------------------------------------")
$stream.WriteLine("$LogTime $ExecUser | Set expire date for user $setenddateuser to $usernewenddate")
$stream.close()

What am I doing wrong here that the handle for this file is not released for someone else to use?

Creating a stream basically blocks the access or the creation of other streams for any files, unless it's al xlsx in sharemode, what I do with the log similar logs is to use add-content.

Ie:

Add-content -value "test" -path $logRoute

Sorry for any typos, I'm on my cell atm. But that should fix your issue

Have you tried using a fine-grained .NET mutex? Each time you need to log a message, lock the mutex, use Add-Content to append the message, then release the mutex. That should make sure the file is never opened multiple times simultaneously, which is almost certainly the cause of your problem.

Here's an article on almost exactly this issue.

由于新创建的文件缺少其他用户的写入权限,因此使用ACL命令有助于解决此问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM