gpt4 book ai didi

powershell - “您不能在空值表达式上调用方法”错误

转载 作者:行者123 更新时间:2023-12-02 23:12:51 26 4
gpt4 key购买 nike

我有一个PowerShell脚本,它将根据用户输入将TCP / IP打印机安装到多台计算机上。
脚本运行良好,但我们希望添加保护措施,以使用户不会将打印机意外安装到位于不同子网中另一个站点的 Assets 上。

我添加了以下功能

### Function to compare subnet of Printer and Asset
Function CheckSubnet {
param ($PrinterIP, $ComputerName, $PrinterCaption)
$Printer = Test-Connection -ComputerName $PrinterIP -Count 1
$PrintIP = $Printer.IPV4Address.IPAddressToString
$IPSplit = $PrintIP.Split(".")
$PrinterSubnet = ($IPSPlit[0]+"."+$IPSplit[1]+"."+$IPSplit[2])
$getip = Test-Connection -ComputerName $ComputerName -Count 1
$IPAddress = $getip.IPV4Address.IPAddressToString
$AssetIP = $IPAddress.Split(".")
$AssetSubnet = ($AssetIP[0]+"."+$AssetIP[1]+"."+$AssetIP[2])
If ($PrinterSubnet -ne $AssetSubnet){
Write-Host $ComputerName 'is not on the same subnet as ' $PrinterCaption
$UserInput = Read-Host 'do wish to install anyway? Y/N'

If ($UserInput -eq "Y") {
} Else {
Continue
}
} Else {
}
}

现在,当我运行脚本时,出现以下错误返回

You cannot call a method on a null-valued expression.
At C:\Users\sitblsadm\Desktop\Untitled1.ps1:28 char:1
+ $IPSplit = $PrintIP.Split(".")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

Cannot index into a null array.
At C:\Users\sitblsadm\Desktop\Untitled1.ps1:29 char:1
+ $PrinterSubnet = ($IPSPlit[0]+"."+$IPSplit[1]+"."+$IPSplit[2])
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray

我了解空数组,因为没有给 $IPSplit赋值,
但是,我对“您不能在空值表达式上调用方法”的理解是,没有为它分配任何值,但是在这种情况下,我试图为它分配一个值。

最佳答案

如果Test-Connection -ComputerName $PrinterIP -Count 1失败,则$Printer$PrintIP的值将为$null。您需要更多错误处理,或者使用try-catch-finally块,或者检查$?自动变量并抛出错误:

$Printer = Test-Connection -ComputerName $PrinterIP -Count 1
if(-not $?){
throw "Printer unavailable"
}

Explanation:$?包含最后一个操作的执行状态。如果最后一个操作成功,则包含TRUE;如果失败,则包含FALSE。

关于powershell - “您不能在空值表达式上调用方法”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31309614/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com