[英]What is causing the error “You cannot call a method on a null-valued expression.”
I am trying to create a script that will uninstall software listed in the variable $packages我正在尝试创建一个脚本来卸载变量 $packages 中列出的软件
When running my code i get the below error and cannot figure what is causing this.运行我的代码时,我收到以下错误,无法弄清楚是什么原因造成的。
You cannot call a method on a null-valued expression.
At line:7 char:3
+ $app.Uninstall()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
some of the items within Packages will uninstall but not all and if i add an additional fake package to the start then they will all uninstall and produce the same error for that fake package which has left me a little confused as to why this happens. Packages 中的一些项目将卸载但不是全部,如果我在开始时添加一个额外的假包,那么它们将全部卸载并为该假包产生相同的错误,这让我有点困惑为什么会发生这种情况。
My code is我的代码是
$packages = @("Package 1 (Transport) TEST", "Package 2 TEST", "Package 3 TEST", "Package 4
TEST", "Package 5 TEST", "Package 6 TEST", "Package 7 TEST", "Package 8 TEST", "Package 9
TEST", "Package 10 TEST", "Package 11 TEST", "Package 12 TEST")
foreach($package in $packages){
$app = Get-WmiObject -Class Win32_Product | Where-Object {
$_.Name -match "$package"
}
$app.Uninstall()
}
any help would be greatly appreciated任何帮助将不胜感激
That error means that nothing is assigned to $app
- in other words, there were no discoverable instance of Win32_Product
that satisfied the Where-Object
condition $_.Name -match "$package"
.该错误意味着没有分配给
$app
- 换句话说,没有可发现的Win32_Product
实例满足Where-Object
条件$_.Name -match "$package"
。
You can either rewrite your code slightly to check whether $app
has a value or not:您可以稍微重写您的代码以检查
$app
是否具有值:
foreach($package in $packages){
$app = Get-WmiObject -Class Win32_Product | Where-Object {
$_.Name -match "$package"
}
# Let's make sure we actually got something
if($app){
$app.Uninstall()
}
}
Or, perhaps preferably, do another loop over the 0 or more objects that $app
might contain (in the case where a package name matches multiple installed products):或者,也许最好对
$app
可能包含的 0 个或多个对象执行另一个循环(在包名称匹配多个已安装产品的情况下):
foreach($package in $packages){
$apps = Get-WmiObject -Class Win32_Product | Where-Object {
$_.Name -match "$package"
}
# if `$apps` is empty/$null, the loop will simply run 0 times :)
foreach($app in $apps){
$app.Uninstall()
}
}
Mathias answer resolved my error issues however i had a further problem where one of the Packages was not being found for some reason. Mathias 的回答解决了我的错误问题,但是我还有一个问题,即由于某种原因没有找到其中一个包。 (I suspect this is due to Brackets in packages name)
(我怀疑这是由于包名称中的括号)
I modified my Script as below, In my use case i want everything from the same vedor uninstalled so this works fine for me.我修改了我的脚本,如下所示,在我的用例中,我希望卸载同一个 vedor 中的所有内容,因此这对我来说很好用。
$app = Get-WmiObject -Class Win32_Product | Where-Object {$_.Vendor -match "[Vendor Name]"}
$app.Uninstall()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.