Log in  \/ 
x
x
x
Register  \/ 
x

22
July
2014

String was not recognized as a valid DateTime

Many SCSM customizers who use Service Manager with non-US regional settings and try to set DateTime value using SMLets cmdlets in PowerShell scripts meet ‘String was not recognized as a valid DateTime’ error.

Recently I have met again such an issue and decided to write a short post how to solve that. Of course, you can change the regional settings to US ones for your SCSM management server but sometimes that leads to unpleasant consequences like an ambiguity with dates in emails, logs, etc.

The solution, as usual, is very simple. Let’s set US culture for your script’s PowerShell run-time.  We will use ‘try-finally’ approach to revert explicitly our initial settings. Here I already used this trick.

#------------ save culture----------------------
$OldCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
$OldUICulture = [System.Threading.Thread]::CurrentThread.CurrentUICulture

try
{
#------------ set culture ----------------------
$culture = New-Object System.Globalization.CultureInfo("en-US")
System.Threading.Thread]::CurrentThread.CurrentCulture = $culture
[System.Threading.Thread]::CurrentThread.CurrentUICulture = $culture 

#----------- your code here --------------------
#----------- your code here --------------------
#----------- your code here --------------------
#----------- your code here --------------------
#----------- your code here --------------------
}

finally
{
#----------- recover culture --------------------
[System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
[System.Threading.Thread]::CurrentThread.CurrentUICulture = $OldUICulture
}

I have attached a sample of the PS script for your convenience. Of course, you can use this code not only for SMlets scripts.

Download

P.S. By the way, if you find this information useful, I would personally appreciate for your evaluation of our products. Be sure, they are worth of a try.

Categories: System Center 2012, System Center 2012 Service Manager

Marat Kuanyshev

Leave a comment

You are commenting as guest.

This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.