none
Property Bag not returning variable data.

    Question

  • I have this script I'm running with a two state PowerShell monitor module I created.  It returns all the property bag data correctly for Server 2012 & 2012 R2. The script works on 2008R2 but I am not receiving the description results in the property bag. I'm only getting the hard coded part of the description I'm inserting and not the content from my variable $results2.  I walked through the script one line at a time on 2008R2 servers and my variables all have data.  I'm not sure what's happening. 

    I borrowed the code from http://blogs.msdn.com/b/wei_out_there_with_system_center/archive/2013/10/23/opsmgr-using-wizards-to-create-powershell-based-monitors.aspx and http://blogs.msdn.com/b/wei_out_there_with_system_center/archive/2013/10/04/opsmgr-monitoring-certificate-expiry-with-a-powershell-based-monitor.aspx?CommentPosted=true#commentmessage

    sl Cert:\LocalMachine\My
    $thresholdindays = 90
    $ExpiredCerts = Get-ChildItem -Recurse | where { $_.notafter -le (get-date).AddDays($thresholdindays)-AND $_.notafter -gt (get-date)} | Select-Object Subject,FriendlyName,NotAfter,Thumbprint

    $API          = new-object -comObject "MOM.ScriptAPI"
    $PropertyBag  = $API.CreatePropertyBag()
     if($ExpiredCerts.Thumbprint.Length -gt 0)   {
     $OFS = "`r`n"
     $result1 = [system.String]::Join($ofs, $ExpiredCerts)
     $result2 = [string]$result1
     $result2 = $result2 -replace "@{", ""
     $result2 = $result2 -replace "}", ""

        $PropertyBag.AddValue("State","ERROR")
        $PropertyBag.AddValue("Description", 'Expiring Certificates: ' + $result2)
      }
      else   { 
        $PropertyBag.AddValue("State","OK")
        $PropertyBag.AddValue("Description", "ALL GOOD !!")
        }

    $PropertyBag

    Tuesday, May 26, 2015 8:09 PM

All replies

  • Try taking the calculation out of the property bag, and instead pass a variable that is already evaluated.

    e.g.

    <$result2 calculations>
    $Status = 'Expiring Certificates: ' + $result2

    $PropertyBag.AddValue("Description", "$Status")

    Thursday, May 28, 2015 12:31 AM
  • Hi Steve,

    Thanks for replying.  It does not appear to like that either.  When I read your solution, it made good sense.  I don't get it because the output for the description still has "Expiring Certificates" but not the rest of the output.  I walked through the code and the $description variable has the full string.  Here is the code I'm using now.

    sl Cert:\LocalMachine\My

    $thresholdindays = 90

    $ExpiredCerts = Get-ChildItem -Recurse | where { $_.notafter -le (get-date).AddDays($thresholdindays)-AND $_.notafter -gt (get-date)} | Select-Object Subject,FriendlyName,NotAfter,Thumbprint

    $API          = new-object -comObject "MOM.ScriptAPI"

    $PropertyBag  = $API.CreatePropertyBag()

    if(!$ExpiredCerts)   {

        $PropertyBag.AddValue("State","OK")

        $PropertyBag.AddValue("Description", "ALL GOOD !!") 

      }

      else   { 

        $OFS = "`r`n"

        $result1 = [system.String]::Join($ofs, $ExpiredCerts)

        $result2 = [string]$result1

        $result2 = $result2 -replace "@{", ""

        $result2 = $result2 -replace "}", ""

        $description = 'Expiring Certificates: ' + $result2

        $PropertyBag.AddValue("State","ERROR")

        $PropertyBag.AddValue("Description", $description)

        }

    $PropertyBag

    Monday, June 1, 2015 5:08 PM
  • replace $PropertyBag with $API.Return($PropertyBag) and run it in powershell, see if you are getting output in XML? if not there's some problem with script


    Faizan

    Monday, June 1, 2015 7:51 PM
  • Try enclosing your variable in quotes - since you are passing a string with spaces in it:

    $PropertyBag.AddValue("Description", "$description")

    Wednesday, June 3, 2015 11:40 AM
  • That gives the same output which is puzzling to me.
    Friday, June 5, 2015 4:32 PM
  • I received a PowerShell exception...

    Exception calling "Return" with "1" argument(s): "The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))"

    At line:1 char:1

    + $API.Return($PropertyBag)

    + ~~~~~~~~~~~~~~~~~~~~~~~~~

        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

        + FullyQualifiedErrorId : ComMethodTargetInvocation

    Friday, June 5, 2015 4:33 PM
  • Couple of things to try -

    I believe the correct format is just "$PropertyBag" at the end of your script.  The $api.return($propertybag) while proper, is a vbscript format, or a valid format for testing out of SCOM.

    Start placing trace logs in your script that output to a text file, and include any $error[0] messages along the way.  This is the way I see how my powershell scripts behave inside the discovery/monitor rules when it's running.

    e.g

    $results = ""
    $exportpath = "\\yourPC\c$\temp\" + $computername + "-log.txt" ($computername resolves to the target host running the script, if passing it in a parameter, make sure permissions are possible to write logs on the destination)

    $results += "Running discovery..."

    $error.clear()

    <do stuff>

    $results += " my variable: " + $variable

    $PropertyBag

    $results += $error
    $results | out-file $exportpath

    Then check your log text file to see various output and errors being generated.  Could be something else in your script altogether causing the problem.

    • Proposed as answer by mofayew Thursday, July 2, 2015 8:10 PM
    • Unproposed as answer by Hollisorama Thursday, July 2, 2015 8:16 PM
    Saturday, June 6, 2015 10:58 PM
  • Thanks Steve.  The weird thing is that it works perfectly fine on Server 2012 R2.  Just not on 2008 R2.
    Tuesday, June 9, 2015 8:27 PM
  • Try to find community management pack. Better solution if you will create own instance for each certificate and you will monitor it with cookdown.

    $Api = New-Object -ComObject "MOM.ScriptAPI"
    $Certs = gci Cert:\LocalMachine\My -Recurse
    foreach ($Cert in $Certs) {
    	$Bag = $Api.CreatePropertyBag()
    	$TimeSpan = $Cert.NotAfter - [DateTime]::Now
    	$Bag.AddValue("Thumbprint", $Cert.Thumbprint)
    	$Bag.AddValue("ExpAfter", $TimeSpan.Days)
    	$Bag
    }
    After PSScript just create two or three states with condition detection modules where you will compare Thumbprint (use this field in your certificate class) and days with threshold values.
    <Expression>
    	<And>
    		<Expression>
    			<SimpleExpression>
    				<ValueExpression>
    					<XPathQuery Type="String">Property[Name="Thumbprint"]</XPathQuery>
    				</ValueExpression>
    				<Operator>Equal</Operator>
    				<ValueExpression>
    					<Value Type="String">$Target/Property[Type="MyCertClass"]/Thumbprint$</Value>
    				</ValueExpression>
    			</SimpleExpression>
    		<Expression>
    		<Expression>
    			<SimpleExpression>
    				<ValueExpression>
    					<XPathQuery Type="Integer">Property[Name="ExpAfter"]</XPathQuery>
    				</ValueExpression>
    				<Operator>Greater</Operator>
    				<ValueExpression>
    					<Value Type="Integer">$Config/CriticalThreshold$</Value>
    				</ValueExpression>
    			</SimpleExpression>
    		<Expression>
    	</And>
    </Expression>


    Vladimir Zelenov | http://systemcenter4all.wordpress.com

    Wednesday, June 10, 2015 9:27 AM
  • That's a good suggestion too Vladamir.  I had though about adding a value to the property bag for each attribute I'm retrieving.  I had not thought about doing a foreach operation though.  That might yield more of what I want anyway.  Right now, the description comes though with all certs that are expiring in one description field.  This might make the alert more legible and solve my issue with actually getting data returned. 

    Again, the weird thing is that the current script works fine in Windows Server 2012 R2 but has issue on 2008 R2.  On the 2008R2 servers we are using PS 3.0 and on 2012 R2 4.0

    Wednesday, June 10, 2015 6:08 PM
  • Just in case your problem still exists: try to execute the script from a PowerShell window, rather than from the ISE. This way you won't get the PowerShell exception above.
    Wednesday, May 10, 2017 9:53 PM
  • That's a good suggestion too Vladamir.  I had though about adding a value to the property bag for each attribute I'm retrieving.  I had not thought about doing a foreach operation though.  That might yield more of what I want anyway.  Right now, the description comes though with all certs that are expiring in one description field.  This might make the alert more legible and solve my issue with actually getting data returned. 

    Again, the weird thing is that the current script works fine in Windows Server 2012 R2 but has issue on 2008 R2.  On the 2008R2 servers we are using PS 3.0 and on 2012 R2 4.0

    You can call native C# objects from PowerShell. This script should works with any PowerShell version:

    $Api = New-Object -ComObject "MOM.ScriptAPI"
    $Store = New-Object Security.Cryptography.X509Certificates.X509Store([Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine)
    $Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
    foreach ($Cert in $Store.Certificates) {
    	$Bag = $Api.CreatePropertyBag()
    	$TimeSpan = $Cert.NotAfter - [DateTime]::Now
    	$Bag.AddValue("Thumbprint", $Cert.Thumbprint)
    	$Bag.AddValue("ExpAfter", $TimeSpan.Days)
    	$Bag
    }


    Vladimir Zelenov | http://systemcenter4all.wordpress.com

    Monday, July 31, 2017 2:16 PM
  • I received a PowerShell exception...

    Exception calling "Return" with "1" argument(s): "The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))"

    At line:1 char:1

    + $API.Return($PropertyBag)

    + ~~~~~~~~~~~~~~~~~~~~~~~~~

        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

        + FullyQualifiedErrorId : ComMethodTargetInvocation

    The exception means that you've added some invalid type value.

    Vladimir Zelenov | http://systemcenter4all.wordpress.com

    Monday, July 31, 2017 2:21 PM
  • Vladamir,

    Thanks for the reply.  I was thinking about revisiting this at some point.  I've noticed that 2008R2 servers are returning better results now.  I didn't change anything with the script though.

    Monday, July 31, 2017 2:29 PM
  • This worked for me. Thanks GTrevize!
    Monday, February 11, 2019 4:06 PM