【问题标题】:PowerShell get directory of a programPowerShell 获取程序的目录
【发布时间】:2022-01-08 22:53:24
【问题描述】:

我最近写了一个脚本,想和我的同事分享。这是一个简单的复制和粘贴程序,每次运行后都会创建日志文件。问题是我使用了这个: start transcript -Path C:\Users…

该程序运行良好,但如果其他人运行该脚本,它将无法创建日志文件,因为该目录是我的副本。

现在我的问题是:程序是否可以找到每个用户保存脚本的目录,以便它可以在该目录中创建一个子文件夹,然后将日志转储到那里?

提前谢谢你

【问题讨论】:

    标签: powershell directory


    【解决方案1】:

    当前执行脚本所在文件夹的路径可以通过the $PSScriptRoot automatic variable获取:

    Start-Transcript -OutputDirectory $PSScriptRoot
    

    【讨论】:

      【解决方案2】:

      以下是我使用 Start-Transcript cmdlet 记录 PowerShell 会话的方法。它会创建一个日志文件,从该文件运行脚本。

      #Log File Paths
      $Path = Get-Location
      $Path = $Path.ToString()
      $Date = Get-Date -Format "yyyy-MM-dd-hh-mm-ss"
      $Post = "\" + (Get-Date -Format "yyyy-MM-dd-hh-mm-ss") + "-test.log"
      
      $PostLog = $Path + $Post
      $PostLog = $PostLog.ToString()
      
      #Start Transcript
      Start-Transcript -Path $PostLog -NoClobber -IncludeInvocationHeader
      
      #Your Script
      Get-Date
      
      #End Transcript
      Stop-Transcript -ErrorAction Ignore
      
      
      

      【讨论】:

        猜你喜欢
        • 2011-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-13
        • 2023-03-10
        相关资源
        最近更新 更多