[英]PowerShell can't divide a value on some systems
有一個非常奇怪的問題。 我有兩個系統(台式機和筆記本電腦)。 兩者都運行 Windows 10 和 PowerShell 5.1。 在我的桌面上,除法工作沒有問題,但在我的筆記本電腦上,我收到以下 op_Division 錯誤,它說它是一個對象(但除法在其他系統上工作正常)。 我嘗試以某種方式將對象轉換為字符串,但我嘗試的一切都失敗了。
任何人都可以建議我如何讓它在出現故障的系統上進行划分(以及為什么它可以在其他系統上正常工作)?
$width = (Get-WmiObject -Class Win32_DesktopMonitor | Select-Object ScreenWidth).ScreenWidth
$width = $width / 2
#####
Method invocation failed because [System.Object[]] does not contain a method named 'op_Division'.
At line:1 char:1
+ $width = $width / 2
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Division:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
這可能發生,因為$width
是一個數組。 如果您運行$width.PsObject
您可以看到BaseObject
值將是一個可能包含$null
的集合。 當您運行$width[0]
您可能會返回$null
值。 您將需要對當前代碼使用另一個索引。
但是,您可以從Where
開始過濾掉$null
值。
$width = (Get-WmiObject -Class Win32_DesktopMonitor | Where ScreenWidth).ScreenWidth
$width = $width | Foreach-Object { $_ / 2 }
通過您的嘗試,至少在我的系統上, $width
返回一個數組。
$width.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
$width
1920
$width.PsObject | Select-Object BaseObject
BaseObject
----------
{$null, 1920}
$width[0] # Index 0 contains the $null
$width[1] # Index 1 contains the size
1920
您有多個監視器並且 Get-WMIObject 正在返回一個數組,因此請使用以下命令:
Get-WmiObject -Class Win32_DesktopMonitor | Select-Object ScreenWidth | ForEach {
[Double]$width = [Double]$_.ScreenWidth[0]
$width = $width / 2
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.