question

Franois-0770 avatar image
0 Votes"
Franois-0770 asked IanXue-MSFT commented

Creating Custom WMI Class for profile size

Hi,

I am creating a script to retrieve the user's profil in a custom WMI class. But I get a failure on set-wmiclass...


Set-WMIInstance : Tentative de placement d’une instance sans clé définie.
Au caractère Ligne:1 : 1
+ Set-WMIInstance -class $Str_ClassName -argument $arglist
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation : (:) [Set-WmiInstance], ManagementException
+ FullyQualifiedErrorId : SetWMIManagementException,Microsoft.PowerShell.Commands.SetWmiInstance

 #Create Class
 <#
 Function New-WMI-Class {
    
     $newClass = New-Object System.Management.ManagementClass("root\cimv2", [String]::Empty, $null);
    
     $newClass["__CLASS"] = "ProfilSize";
    
     $newClass.Properties.Add("Name", [System.Management.CimType]::String, $false)
     $newClass.Properties["ID"].Qualifiers.Add("key", $true)
     $newClass.Properties["ID"].Qualifiers.Add("read", $true)
    
     $newClass.Properties.Add("Nombre", [System.Management.CimType]::String, $false)
     $newClass.Properties["Name"].Qualifiers.Add("read", $true)
    
     $newClass.Properties.Add("Taille", [System.Management.CimType]::String, $false)
     $newClass.Properties["State"].Qualifiers.Add("read", $true)
    
     $newClass.Put()
    
 }
 #>
    
 Function New-WMIClass {
     <#
     .SYNOPSIS
     This function help to create a new WMI class.
     
     .DESCRIPTION
     The function allows to create a WMI class in the CimV2 namespace.
     Accepts a single string, or an array of strings.
     
     .PARAMETER ClassName
     Specify the name of the class that you would like to create. (Can be a single string, or a array of strings).
     
     .PARAMETER NameSpace
     Specify the namespace where class the class should be created.
     If not specified, the class will automatically be created in "Root\cimv2"
     
     .EXAMPLE
     New-WMIClass -ClassName "PowerShellDistrict"
     Creates a new class called "PowerShellDistrict"
     .EXAMPLE
     New-WMIClass -ClassName "aaaa","bbbb"
     Creates two classes called "aaaa" and "bbbb" in the Root\cimv2
     
     .NOTES
     Version: 1.0
     Author: Stephane van Gulick
     Creation date:16.07.2014
     Last modification date: 16.07.2014
         
     .LINK
     www.powershellDistrict.com
     
     .LINK
     http://social.technet.microsoft.com/profile/st%C3%A9phane%20vg/
     
     #>
    
     Param(
     [Parameter(Mandatory=$true,valueFromPipeLine=$true)][string[]]$ClassName,
     [Parameter(Mandatory=$false)][string]$NameSpace = "root\cimv2" 
     )
      
     foreach ($NewClass in $ClassName){
     
         if (!(Get-WMIClass -ClassName $NewClass -NameSpace $NameSpace)){
            
         write-verbose "Attempting to create class $($NewClass)"
         $WMI_Class = ""
         $WMI_Class = New-Object System.Management.ManagementClass($NameSpace, $null, $null)
         $WMI_Class.name = $NewClass
         $WMI_Class.Put() | out-null
     
         write-host "Class $($NewClass) created."
     
         }else{write-host "Class $($NewClass) is already present. Skiping.."}
     }
     
 }
    
 Function New-WMIProperty {
     <#
     .SYNOPSIS
     This function help to create new WMI properties.
     
     .DESCRIPTION
     The function allows to create new properties and set their values into a newly created WMI Class.
     Event though it is possible, it is not recommended to create WMI properties in existing WMI classes !
     
     .PARAMETER ClassName
     Specify the name of the class where you would like to create the new properties.
     
     .PARAMETER PropertyName
     The name of the property.
     
     .PARAMETER PropertyValue
     The value of the property.
     
     .EXAMPLE
     New-WMIProperty -ClassName "PowerShellDistrict" -PropertyName "WebSite" -PropertyValue "www.PowerShellDistrict.com"
     
     .NOTES
     Version: 1.0
     Author: Stephane van Gulick
     Creation date:16.07.2014
     Last modification date: 16.07.2014
     
     .LINK
     www.powershellDistrict.com
     
     .LINK
     http://social.technet.microsoft.com/profile/st%C3%A9phane%20vg/
     
     #>
     
     
    
     [CmdletBinding()]
     Param(
     [Parameter(Mandatory=$true)]
     [ValidateScript({
     $_ -ne ""
     })]
     [string]$ClassName,
     
     [Parameter(Mandatory=$false)]
     [string]$NameSpace="Root\cimv2",
     
     [Parameter(Mandatory=$true)][string]$PropertyName,
     [Parameter(Mandatory=$false)][string]$PropertyValue=""
     
     
     )
     begin{
         [wmiclass]$WMI_Class = Get-WmiObject -Class $ClassName -Namespace $NameSpace -list
     }
     Process{
         write-verbose "Attempting to create property $($PropertyName) with value: $($PropertyValue) in class: $($ClassName)"
         $WMI_Class.Properties.add($PropertyName,$PropertyValue)
         Write-Output "Added $($PropertyName)."
     }
     end{
         $WMI_Class.Put() | Out-Null
         [wmiclass]$WMI_Class = Get-WmiObject -Class $ClassName -list
         return $WMI_Class
     }
 }
    
 [String]$Str_ClassName="ProfilSize"
 [Array]$Arr_Property=@("Name","Compte","Total")
    
 #Création de la classe
 New-WMIClass -ClassName "$Str_ClassName"
    
 #On créer les propriétés
 ForEach ($Prop in $Arr_Property) {
    
     New-WMIProperty -ClassName "$Str_ClassName" -PropertyName "$Prop"
 # -PropertyValue "www.PowerShellDistrict.com"
    
 }
    
    
 [array]$Arr_users = Get-ChildItem -Path "$envsystemdrive\Users"
    
    
 $Arr_users | ForEach-Object {
            
         $colItems = (Get-ChildItem $env:systemdrive\Users\$($_.Name) -recurse -Force -ErrorAction SilentlyContinue | Measure-Object -property length -sum)
         $DirectorySizeMB = [math]::Round($colItems.sum / 1MB,1)
         Write-host "$($_.Name): $DirectorySizeMB Mo"
    
         $arglist = @{
  Name    = $($_.Name)
  Compte  = $($colItems.Count).ToString()
  Total = $($colItems.sum).ToString()
  }
  Set-WmiInstance -$Str_ClassName -Arguments $arglist
    
 }


windows-server-powershellwindows-server-management
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi,
Thank you for sharing. Please help to "Accept Answer" to close this question.
Best Regards,
Ian

0 Votes 0 ·
Franois-0770 avatar image
0 Votes"
Franois-0770 answered

Hi,

Finally

 [String]$Str_ClassName="ProfileSize"
 [Array]$Arr_Property=@("Name","Count","Total","DateCreate","TreatmentDuration")
 $WMI_Class = ""
 $WMI_Class = New-Object System.Management.ManagementClass("Root\cimv2", $null, $null)
 $WMI_Class.name = $Str_ClassName
    
 #Test class existence and remove it if existing
 $class = Get-WmiObject -Class $Str_ClassName -List -Namespace 'root\cimv2';
 If ($class -ine $null) {Remove-WmiObject -Class $Str_ClassName}
    
 #Création de la classe
 $WMI_Class["__CLASS"] = $Str_ClassName
    
        
 #Get userprofiles
 [array]$Arr_users = Get-ChildItem -Path "$envsystemdrive\Users"
    
 #Instance creation
 $Arr_users | ForEach-Object {
    
         #Start the clock
         $stopwatch=[system.diagnostics.stopwatch]::StartNew()
            
         $colItems = (Get-ChildItem $env:systemdrive\Users\$($_.Name) -recurse -Force -ErrorAction SilentlyContinue | Measure-Object -property length -sum)
         $DirectorySizeMB = [math]::Round($colItems.sum / 1MB,1)
         Write-host "$($_.Name): $DirectorySizeMB Mo"
    
         #Stop the clock
         $stopwatch.stop()
    
         $arglist = @{        
             Name    = $($_.Name)                    #Profile name
             Count  = $($colItems.Count).ToString()  #How many files in the profile?
             #Total = $($colItems.sum).ToString()    
             Total = $DirectorySizeMB.ToString()     #Total size for that profil?
             DateCreate=$(get-date).tostring()       #When that profil was evaluate?
             TreatmentDuration=$([math]::Round($($stopwatch.Elapsed).totalseconds,1)).tostring() #How much time to calculate that profile in second.
         }
            
         $WMI_Class.Properties.Add("Name", [System.Management.CimType]::String, $false)
         $WMI_Class.Properties["Name"].Qualifiers.Add("key", $true)
            
         $WMI_Class.Properties.Add("Total", [System.Management.CimType]::String, $false)
         $WMI_Class.Properties["Total"].Qualifiers.Add("key", $true)
            
         $WMI_Class.Properties.Add("Count", [System.Management.CimType]::String, $false)
         $WMI_Class.Properties["Count"].Qualifiers.Add("key", $true)
            
         $WMI_Class.Properties.Add("DateCreate", [System.Management.CimType]::String, $false)
         $WMI_Class.Properties["DateCreate"].Qualifiers.Add("key", $true)
            
         $WMI_Class.Properties.Add("TreatmentDuration", [System.Management.CimType]::String, $false)
         $WMI_Class.Properties["TreatmentDuration"].Qualifiers.Add("key", $true)
            
         $WMI_Class.Put()
            
         Set-WmiInstance -Class $Str_ClassName -Puttype CreateOnly -Argument $arglist    
    
 }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

IanXue-MSFT avatar image
0 Votes"
IanXue-MSFT answered

Hi,
Please check the value of $arglist and $Str_ClassName. Make sure the key-value pairs in the $arglist match the properties of the the class $Str_ClassName.

Best Regards,
Ian

============================================
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.