对程序进行这些设置Win-PS2EXE:
这样,当单击
exe
文件时,控制台就会显示。
这段代码:
$inf_file = "$PSScriptRoot\setup-files\install.inf"
write-host """$inf_file"""
timeout 10
假设新可执行文件的路径是
W:\Apps\Install Scheme.exe
这意味着
$inf_file
在这里W:\Apps\setup-files\install.inf
当我单击转换后的 exe 文件时,我得到了这个。
有什么方法可以获取
W:\Apps\setup-files\install.inf
的正确路径,以便可执行文件在单击时识别自身的位置。
我认为
$PSScriptRoot
会起作用。
我不知道如何解决这个问题,因为 exe 文件最终将取决于知道它的位置。
这是可以实现这一点的代码。
Function Get-PSScriptPath {
<#
.SYNOPSIS
Returns the current filepath of the .ps1 or compiled .exe with Win-PS2EXE.
.DESCRIPTION
This will return the path of the file. This will work when the .ps1 file is
converted with Win-PS2EXE
.NOTES
Author: Ste
Date Created: 2021.05.03
Tested with PowerShell 5.1 and 7.1.
Posted here: https://stackoverflow.com/q/60121313/8262102
.PARAMETER None
NA
.INPUTS
None. You cannot pipe objects to Get-PSScriptPath.
.OUTPUTS
Returns the current filepath of the .ps1 or compiled .exe with Win-PS2EXE.
.EXAMPLE (When run from a .ps1 file)
PS> Get-PSScriptPath
PS> C:\Users\Desktop\temp.ps1
.EXAMPLE (When run from a compiled .exe file with Win-PS2EXE.
PS> Get-PSScriptPath
PS> C:\Users\Desktop\temp.exe
#>
if ([System.IO.Path]::GetExtension($PSCommandPath) -eq '.ps1') {
$psScriptPath = $PSCommandPath
} else {
# This enables the script to be compiles and get the directory of it.
$psScriptPath = [System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName
}
return $psScriptPath
}
Get-PSScriptPath
提供实用、简洁的替代方案 (PSv3+),始终将脚本路径报告为完整路径:
单行:
$scriptDir = if (-not $PSScriptRoot) { Split-Path -Parent (Convert-Path ([Environment]::GetCommandLineArgs()[0])) } else { $PSScriptRoot }
注释表格:
$scriptDir = if (-not $PSScriptRoot) { # $PSScriptRoot not defined?
# Get the path of the executable *as invoked*, via
# [environment]::GetCommandLineArgs()[0],
# resolve it to a full path with Convert-Path, then get its directory path
Split-Path -Parent (Convert-Path ([Environment]::GetCommandLineArgs()[0]))
}
else {
# Use the automatic variable.
$PSScriptRoot
}