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

时间:2017-10-23 15:52:43

标签: powershell

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

1508422683779

然后我可以称之为

$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)
}

失败,错误代码为1639。 如果这不起作用,如何在使用$ PSScriptRoot?

时引用子目录

2 个答案:

答案 0 :(得分:0)

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

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)
}

答案 1 :(得分:0)

请注意,$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在技术上是一个数组,我嵌入"以防路径包含任何空格。

相关问题