繁体   English   中英

Powershell引用当前目录和子文件夹

[英]Powershell referencing current directory and subfolder

我使用以下代码引用当前脚本目录中的文件

$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

然后我可以这样称呼它

try {
WriteLog("Installing...")
$installresult = (Start-Process msiexec.exe -ArgumentList "/i 
$PSScriptRoot\InstallPrism6.msi /qn /norestart" -Wait -PassThru).ExitCode
WriteLog("Installation finished with return code: $installresult")
}
catch {
    WriteLog($_.Exception.Message)
}

这很好。 但是,如果我想像这样子目录中的文件引用

try {
WriteLog("Installing...")
$installresult = (Start-Process msiexec.exe -ArgumentList "/i $PSScriptRoot 
+ \test\InstallPrism6.msi /qn /norestart" -Wait -PassThru).ExitCode
WriteLog("Installation finished with return code: $installresult")
}
catch {
    WriteLog($_.Exception.Message)
}

它失败,错误代码为1639。如果这不起作用,使用$ PSScriptRoot时如何引用子目录?

尝试在路径中不要留空格。 使用变量构建字符串时,不需要连接。 这与引用子文件夹无关。

try {
WriteLog("Installing...")
$installresult = (Start-Process msiexec.exe -ArgumentList "/i ${PSScriptRoot}\test\InstallPrism6.msi /qn /norestart" -Wait -PassThru).ExitCode
WriteLog("Installation finished with return code: $installresult")
}
catch {
    WriteLog($_.Exception.Message)
}

请注意, $PSScriptRoot变量是在PowerShell 3.0及更高版本上预定义的,因此仅在尚未定义该变量时才需要。 我相信您要执行的操作的正确语法应如下所示:

if ( -not $PSScriptRoot ) {
  $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
}

try {
  WriteLog "Installing..."
  $installresult = (Start-Process msiexec.exe -ArgumentList "/i","`"$PSScriptRoot\test\InstallPrism6.msi`"","/qn","/norestart" -Wait -PassThru).ExitCode
  WriteLog "Installation finished with return code: $installresult"
}
catch {
  WriteLog $_.Exception.Message
}

-ArgumentList从技术上讲是一个数组,如果路径包含任何空格,我会嵌入"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM