【问题标题】:Powershell vs variable file locationPowershell vs 变量文件位置
【发布时间】:2021-05-01 06:11:09
【问题描述】:

我习惯于在自动化脚本中使用%~dp0,以确保无论部署文件夹放在哪里都能找到我的文件。

%~dp0 在 PowerShell 中效果不佳,$PSScriptRoot$PSCommandPath 对用户不友好

我可以让这段代码卸载并安装应用程序而不会出现任何问题。问题是我必须声明并不总是正确的文件位置。

很好,但必须声明位置。

$RmvAppName = Get-WmiObject -Class Win32_Product | Where-Object{$_.Name -eq "chrome"}
$RmvAppName.Uninstall() | Out-Null
Start-Process msiexec.exe -ArgumentList '/i c:\deploy\microsoft\edge.msi /passive ALLUSERS=1' | Out-Null

如果我尝试使用对我不起作用的位置变量。我试过Set-LocationGet-Location$PSScriptRoot$PSCommandPath,但没有任何效果。我只是在 PowerShell 中寻找能够为我提供 %~dp0 的功能和 PowerShell 的强大功能的东西。

不好!

$RmvAppName = Get-WmiObject -Class Win32_Product | Where-Object{$_.Name -eq "chrome"}
$location = Get-Location
$RmvAppName.Uninstall() | Out-Null
#Start-Process msiexec.exe -ArgumentList '/i $(location)\edge.msi /passive ALLUSERS=1'

提前感谢大家的帮助。

【问题讨论】:

    标签: powershell-3.0 powershell-4.0


    【解决方案1】:

    也许这会有所帮助?

    PS> $RmvAppName = Get-WmiObject -Class Win32_Product | Where-Object{$_.Name -eq "GO Contact Sync Mod"}
    
    PS> $RmvAppName.Installsource
    \\ComputerMentor2\CMShared\NAS-Downloads\Test\
    

    奇怪的是,即使我安装了“chrome”,我也没有得到响应。

    您可能想阅读this article,了解为什么不使用 Win32_Product。

    HTH

    【讨论】:

    • 重要:链接为什么不去查询Win32_Product
    【解决方案2】:

    申请Split-Path cmdlet如下:

    Split-Path -Path $MyInvocation.MyCommand.Path -Parent
    

    $MyInvocation.MyCommand | Split-Path -Parent
    

    解释

    阅读How-to: Pass Command Line arguments (Parameters) to a Windows batch file.中的与批处理脚本相关的链接段落:

    %~dp0 将返回驱动器和批处理脚本的路径

    在 PowerShell 脚本中,您可以从 $myInvocation automatic variable 获取相同的信息:

    $MyInvocation

    包含有关当前命令的信息,例如名称, 参数、参数值以及有关如何执行命令的信息 被启动、调用或调用,例如脚本的名称 调用当前命令。

    $MyInvocation 仅为脚本、函数和脚本填充 块。您可以使用中的信息 System.Management.Automation.InvocationInfo 对象 $MyInvocation 在当前脚本中返回,如路径和 脚本文件名 ($MyInvocation.MyCommand.Path) ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 2016-09-28
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 2013-06-14
      相关资源
      最近更新 更多