我有一个旧脚本,这是我刚开始使用Powershell时写的第一个脚本。它使用Get-CimInstance -ClassName Win32_ComputerSystem
和Get-CimInstance -ClassName Win32_OperatingSystem
。将其废弃后可在某些用户系统上使用,然后发现某些用户对WMI具有某种奇怪的权限问题,并且无法使用该脚本。就我个人而言,我从未遇到过任何问题,也从未想到其他人会这样做。
因此,我希望摆脱WMI / CIM实例,并用.NET命令或其他在PowerShell脚本中使用的实例替换这些实例。除了WMI / CIM实例,脚本中还有其他要使用的东西吗?请参阅下面我要更改的脚本
$Comp = (Get-CimInstance -ClassName Win32_ComputerSystem);
$DRole = ($Comp).DomainRole;
switch ($DRole)
{
0 {$DominRole = 'Standalone Workstation'}
1 {$DominRole = 'Member Workstation'}
2 {$DominRole = 'Standalone Server'}
3 {$DominRole = 'Member Server'}
4 {$DominRole = 'Backup Domain Controller'}
5 {$DominRole = 'Primary Domain Controller'}
}
$PhyMem = [string][math]::Round(($Comp).TotalPhysicalMemory/1GB, 1);
$FreePhyMem = [string][math]::Round((Get-CimInstance -ClassName Win32_OperatingSystem).FreePhysicalMemory/1024/1024, 1);
$cpux = (Get-WmiObject Win32_Processor).Name;
$GBMem = $PhyMem + ' GB Physical Memory (' + $FreePhyMem + ' GB Free)';
Return $DominRole + ' - ' + $GBMem + '/' + $cpux
答案 0 :(得分:0)
如果您至少使用PowerShell 5.1,Get-ComputerInfo
将提供很多此类信息。您可以看到它提供的相关属性...
PS> Get-ComputerInfo -Property 'CsDomainRole', '*Memory*', '*Processor*'
否则,您可以使用System.Management
namespace中的类以直接查询WMI的方式,就像Get-WmiObject
在幕后...
$selectedProperties = 'DomainRole', 'TotalPhysicalMemory'
# https://docs.microsoft.com/dotnet/api/system.management.selectquery
$query = New-Object -TypeName 'System.Management.SelectQuery' `
-ArgumentList ('Win32_ComputerSystem', $null, $selectedProperties)
# https://docs.microsoft.com/dotnet/api/system.management.managementobjectsearcher
$searcher = New-Object -TypeName 'System.Management.ManagementObjectSearcher' `
-ArgumentList $query
try
{
# https://docs.microsoft.com/dotnet/api/system.management.managementobjectsearcher.get
$results = $searcher.Get()
# ManagementObjectCollection exposes an enumerator but not an indexer
$computerSystem = $results | Select-Object -First 1
$domainRole = $computerSystem['DomainRole']
$totalPhysicalMemory = $computerSystem['TotalPhysicalMemory']
# Do something with $domainRole and $totalPhysicalMemory...
$domainRoleText = switch ($domainRole) {
0 { 'Standalone Workstation' ; break }
1 { 'Member Workstation' ; break }
2 { 'Standalone Server' ; break }
3 { 'Member Server' ; break }
4 { 'Backup Domain Controller' ; break }
5 { 'Primary Domain Controller'; break }
default { $domainRole.ToString() }
}
$totalPhysicalMemoryGB = [Math]::Round($totalPhysicalMemory / 1GB, 1)
}
finally
{
$computerSystem.Dispose()
$results.Dispose()
$searcher.Dispose()
}
很难知道您的问题是WMI本身还是cmdlet在没有更多详细信息的情况下访问它。