问题描述
我习惯于在自动化脚本中使用 %~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-Location
、Get-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'
在此先感谢大家的帮助。
解决方法
也许这会有所帮助?
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
,按如下方式应用 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
) ...