简体   繁体   English

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

[英]'You cannot call a method on a null-valued expression' Error

I have a PowerShell script which will install a TCP/IP printer onto multiple Computers based on user input. 我有一个PowerShell脚本,它将根据用户输入将TCP / IP打印机安装到多台计算机上。 The Script worked fine but we wanted to add in a safeguard so the user could not accidental install the printer onto an Asset at another site on a different subnet. 脚本运行良好,但我们希望添加保护措施,以使用户不会将打印机意外安装到位于不同子网中另一个站点的资产上。

I added the following function 我添加了以下功能

### 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 {
    }
}

Now when I run the script i get the following error return 现在,当我运行脚本时,出现以下错误返回

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

I understand the null array due to $IPSplit not being given a value, But my understanding of "You cannot call a method on a null-valued expression" is that nothing has been assigned to it but in this instance I am trying to assign it a value. 我了解由于未给$IPSplit而导致的空数组,但是我对“您不能在空值表达式上调用方法”的理解是,没有为它分配任何内容,但是在这种情况下,我尝试分配它一个值。

If Test-Connection returns timeouts, $Printer is null. 如果Test-Connection返回超时,则$Printer为空。 If there is a name resolution failure (no PTR record for the printer on the DNS server, and the printer does not respond to WINS), IPV4Address is empty, therefore you get a null string in $PrintIP . 如果存在名称解析失败(DNS服务器上没有打印机的PTR记录,并且打印机不响应WINS),则IPV4Address为空,因此在$PrintIP获得空字符串。 You can fallback to use Destination field as the IP address, or grab plain $PrinterIP , since in this case $PrinterIP will contain an IP address. 您可以回退以将“ Destination字段用作IP地址,或获取普通的$PrinterIP ,因为在这种情况下, $PrinterIP将包含一个IP地址。

if ($PrintIP -eq $null) { continue } # can't add unresponsive printer
if ([String]::IsNullOrEmpty($PrintIP.IPV4Address)) {
    $IPSplit = $PrinterIP.Split(".")
} else {
    $IPSplit = $PrintIP.Split(".")
}

You need to learn how to check against nulls and where. 您需要学习如何检查空值和位置。 Not every cmdlet throws errors and stops the script, they can return null and continue, and then you get null dereferencing exception out of the blue. 并非每个cmdlet都会引发错误并停止脚本,它们可以返回null并继续,然后您会突然获得null取消引用异常。

If Test-Connection -ComputerName $PrinterIP -Count 1 fails, $Printer and $PrintIP will have a value of $null . 如果Test-Connection -ComputerName $PrinterIP -Count 1失败,则$Printer$PrintIP的值将为$null You need some more error handling, either use a try-catch-finally block, or check the $? 您需要更多错误处理,或者使用try-catch-finally块,或者检查$? automatic variable and throw an error: 自动变量并引发错误:

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

Explanation : $? 说明 :$? Contains the execution status of the last operation. 包含最后一个操作的执行状态。 It contains TRUE if the last operation succeeded and FALSE if it failed. 如果最后一个操作成功,则包含TRUE;如果失败,则包含FALSE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM