简体   繁体   English

Powershell写入文件

[英]powershell write to file

I've written a GUI for making changes in AD and I need every action logged. 我已经编写了用于在AD中进行更改的GUI,并且需要记录所有操作。 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. 该GUI被多个用户一次使用并写入一个文件,但是只有写入日志文件的第一人才可以实际写入该文件。 Everyone else has access denied. 其他人的访问被拒绝。 I'm using streamwriter like this. 我正在使用像这样的streamwriter。

$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. 创建流基本上会阻止对任何文件的访问或其他流的创建,除非在共享模式下为xlsx,否则我对类似日志的日志所做的就是使用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? 您是否尝试过使用细粒度的.NET互斥锁? Each time you need to log a message, lock the mutex, use Add-Content to append the message, then release the mutex. 每次您需要记录一条消息时,请锁定互斥锁,使用“ Add-Content附加该消息,然后释放互斥锁。 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命令有助于解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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