I have a PowerShell script which will install a TCP/IP printer onto multiple Computers based on user input. 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.