无法从 PowerShell 脚本写入默认的 Inno Setup 日志文件

Unable to write to the default's Inno Setup log file from a PowerShell script

我想使用 Inno Setup 默认日志文件来记录我的 PowerShell 脚本中的错误,但是当我尝试在它们上面写入时,它似乎总是在使用中。

经过一些研究,我发现临时 SetupName_Version.tmp 正在使用该文件,但我有点坚持使用它。也许创建一个辅助日志文件来记录我的脚本错误是个好主意?我缺少什么?提前致谢。

脚本:

$LogFile=$args[1]
echo "Second arg is $LogFile"
"Second arg is $LogFile" | out-file $LogFile -append
pause

输出:

Second arg is C:\Users\User\AppData\Local\Temp\Setup Log 2020-06-24 #019.txt
out-file : The process cannot access the file 'C:\Users\User\AppData\Local\Temp\Setup Log 2020-06-24 #019.txt'
because it is being used by another process.
At C:\Users\User\AppData\Local\Temp\is-EUMKB.tmp\check_wsl_feature_minimal.ps1:9 char:28
+ "Second arg is $LogFile" | out-file $LogFile -append
+                            ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (:) [Out-File], IOException
    + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand

Press Enter to continue...:

日志文件由安装程序打开。两个程序不能同时写入同一个文件。

您必须在 PowerShell 脚本中登录到不同的文件。如果您想将所有信息都放在一个文件中,您可以在脚本完成后将 PowerShell 脚本日志文件复制到安装程序日志中。您可以使用 LoadStringsFromFile and Log 函数。

var
  ResultCode: Integer;
  Args, PsLogPath: string;
  LogLines: TArrayOfString;
  I: Integer;
begin
  PsLogPath := ExpandConstant('{tmp}\ps.log');
  Args := '-ExecutionPolicy Unrestricted -file "script.ps1" "%s"';
  Args := Format(Args, [PsLogPath]);
  Exec('powershell.exe', Args, '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
  if not LoadStringsFromFile(PsLogPath, LogLines) then
  begin
    Log('PowerShell log file does not exist or cannot be read');
  end
    else
  begin
    Log('PowerShell log:')
    for I := 0 to GetArrayLength(LogLines) - 1 do
    begin
      Log(LogLines[I]);
    end;
  end;
end;

日志文件应采用 UTF-8 编码:Out-File -Encoding utf8


虽然我会使用输出重定向来捕获 PowerShell 脚本生成的所有内容,包括 errors/exceptions,而不是使用 Out-File.

的显式日志记录
Args := '/C powershell -ExecutionPolicy Unrestricted -file "script.ps1" ' +
        '> "%s" 2>&1';
Args := Format(Args, [PsLogPath]);
Exec(ExpandConstant('{cmd}'), Args, '', SW_HIDE, ewWaitUntilTerminated,
     ResultCode);

另一种选择是使用 Start-Transcript