【问题标题】:POwerShell StreamWriterPowerShell StreamWriter
【发布时间】:2023-03-25 22:48:01
【问题描述】:

我有一个应该包含很多相关内容的哈希,其中一件事是日志文件的“句柄”:

$myHash = NewObject psobject -Property @{
    # ...
    "LogFile"  = [System.IO.StreamWriter] $($Env:USERPROFILE+"\Documents\Logs\MsgLog.txt")     
    # ...
}

这失败了(我的翻译):值“C:\Users...”无法转换为“System.IO.StreamWriter”
路径有效。

我需要改变什么?

提前致谢
古力

【问题讨论】:

  • 其余的错误说明了什么?是:"The process cannot access the file '<file name>' because it is being used by another process."
  • 不,它说:“C:\Users\...\MsgLog.txt”不能转换成streamWriter。
  • 该消息应该有更多内容。如果我运行[IO.StreamWriter](get-date),我会收到消息Cannot convert value "6/16/2014 6:37:24 PM" to type "System.IO.StreamWriter". Error: "Invalid cast from 'System.DateTime' to 'System.IO.StreamWriter'.",但如果我运行$a = [IO.StreamWriter]'c:\temp\test.txt';$b = [IO.StreamWriter]'c:\temp\test.txt',我会收到:Cannot convert value "c:\temp\test.txt" to type "System.IO.StreamWriter". Error: "The process cannot access the file 'c:\temp\test.txt' because it is being used by another process."
  • 这也发生在我身上!但是只有在我使用 Keith 的版本之后,停止调试器并且流没有被严重关闭并在调试器中重新启动脚本。如果调试停止,任何提示如何告诉(强制)调试器处置/杀死/关闭该流?现在我需要杀死并重新启动 ISE :(
  • 您可以调用Dispose 方法或清除该值。 (例如$myHash['LogFile'].Dispose()$myHash['LogFile'] = $null

标签: powershell streamwriter


【解决方案1】:

试试这样:

$myHash = New-Object psobject -Property @{
    # ...
    LogFile = new-object System.IO.StreamWriter "$($Env:USERPROFILE)\Documents\Logs\MsgLog.txt"
    # ...

}

注意:除非您在其中添加空格,否则您不必引用键/属性名称。

【讨论】:

    猜你喜欢
    • 2015-04-28
    • 2023-04-05
    • 2019-12-11
    • 2016-08-11
    • 2021-07-10
    • 2014-03-21
    • 2018-07-13
    • 2017-08-16
    • 2020-11-28
    相关资源
    最近更新 更多