PowerShell 获取程序目录
PowerShell get directory of a program
最近写了一个脚本,想分享给同事。这是一个简单的复制和粘贴程序,在每个 运行 之后创建日志文件。问题是我用了这个: start transcript -Path C:\Users…
该程序运行良好,但如果其他人 运行 使用该脚本,它将无法创建日志文件,因为该目录是我的副本。
现在回答我的问题:程序是否可以找到每个用户保存脚本的目录,以便它可以在该目录中创建一个子文件夹,然后将日志转储到那里?
提前致谢
包含当前执行脚本的文件夹的路径可以通过the $PSScriptRoot
automatic variable获得:
Start-Transcript -OutputDirectory $PSScriptRoot
以下是我使用 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
最近写了一个脚本,想分享给同事。这是一个简单的复制和粘贴程序,在每个 运行 之后创建日志文件。问题是我用了这个: start transcript -Path C:\Users…
该程序运行良好,但如果其他人 运行 使用该脚本,它将无法创建日志文件,因为该目录是我的副本。
现在回答我的问题:程序是否可以找到每个用户保存脚本的目录,以便它可以在该目录中创建一个子文件夹,然后将日志转储到那里?
提前致谢
包含当前执行脚本的文件夹的路径可以通过the $PSScriptRoot
automatic variable获得:
Start-Transcript -OutputDirectory $PSScriptRoot
以下是我使用 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