【发布时间】:2015-07-09 06:22:17
【问题描述】:
我有一个 PowerShell 脚本,它将根据用户输入将 TCP/IP 打印机安装到多台计算机上。 脚本运行良好,但我们想添加保护措施,这样用户就不会意外地将打印机安装到不同子网的另一个站点的资产上。
我添加了以下功能
### 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 没有被赋予一个值,
但我对“你不能在空值表达式上调用方法”的理解是没有为它分配任何东西,但在这种情况下,我试图为它分配一个值。
【问题讨论】:
-
$PrintIP 是否包含值?
标签: powershell