我是 PowerShell 的新手,但我發現我可以使用 Substring 來計算變數中字串的右側或左側。它似乎不支持我收到的輸出。我希望有人能指出我正確的方向。感謝您的任何幫助。
檢索計算機名稱的代碼。
$compname = WmiObject -class Win32_ComputerSystem | Select-Object Name
$compname
$compname.Substring(9,0)
這是結果和錯誤:
姓名
計算機-PC 方法呼叫失敗,因為 [Selected.System.Management.ManagementObject] 不包含名為“子字串”的方法。在行:3 字符:1
- $compname.Substring(9,0)
-
CategoryInfo : InvalidOperation: (Substring:String) [], RuntimeException FullyQualifiedErrorId : MethodNotFound
uj5u.com熱心網友回復:
發生此錯誤是因為您嘗試對物件使用 Substring 方法。
看一下,如果我執行與您相同的查詢,它會回傳一個具有“名稱”屬性的物件:

正如 powershell 錯誤所示,您不能直接將 substring 方法呼叫到物件。您必須對字串執行此操作,在本例中為屬性名稱。要解決您的問題,您只需在查詢中呼叫“名稱”屬性。像這樣的東西:
$computerName = (Get-WmiObject Win32_ComputerSystem).Name
之后,您將能夠使用“Substring”方法,因為該查詢回傳一個字串:

如果出現任何其他問題,我很樂意為您提供幫助:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/494956.html
