function Export-Wmi
{
Param (
[Parameter(mandatory=$true)]
[string]
$DbName,
[Parameter(mandatory=$true)]
[array]
$CollectionNames
)
Process {
$CollectionNames |
foreach {
$output = ""
$cmd = ""
$docs = C:\Path\To\Mongo\bin\mongoexport.exe `
--db $DbName `
--collection $_ `
2>$null
$output += "["
$bfirst = $true
foreach( $doc in $docs )
{
if( -not $bfirst )
{
$output += ","
}
$output += $doc
$bfirst = $false
}
$output += "]"
$output | Out-File -FilePath "C:\Path\To\Data\$_.json"
}
}
}
Export-Wmi -DbName "reports" -CollectionNames @("coll1", "coll2" )
Monday, June 21, 2010
Exporting MongoDb with Powershell
I'm just going to leave this right here. This fixes up the output from mongoexport to create an array, suitable for XMLSpy...
Labels:
hth,
powershell
Wednesday, June 2, 2010
Powershell, MongoDB, and WMI
I had reason to write a short cmdlet which converts WMI objects to MongoDB docs. It ain't much, but it works so far:
Hope this helps.
[Cmdlet( VerbsData.ConvertTo, "MongoDoc" )]
public class ConvertToMongoDoc : Cmdlet
{
[Parameter( Mandatory = true, ValueFromPipeline = true )]
public PSObject InputObject { set; get; }
protected override void ProcessRecord()
{
Document converted = (Document)WmiConvert( InputObject.BaseObject );
this.WriteObject( converted );
}
protected object WmiConvert( object obj )
{
if( null == obj )
return null;
object newObj = obj;
Type objType = obj.GetType();
TypeCode objTypeCode = Type.GetTypeCode( objType );
String objTypeName = objType.FullName;
if( objType.IsGenericType )
return obj;
switch ( objTypeCode )
{
case TypeCode.String:
return obj;
}
switch ( objTypeName )
{
case "System.TimeSpan":
return ( (TimeSpan)obj ).Ticks;
case "System.Int16":
case "System.UInt16":
return System.Convert.ToInt32( obj );
case "System.UInt64":
case "System.UInt32":
return System.Convert.ToInt64( obj );
case "System.Byte":
return null;
case "MongoDB.Driver.Document":
return obj;
}
if( objType.IsArray )
{
ArrayList aTmp = new ArrayList();
foreach ( var s in (object[])obj )
{
aTmp.Add( WmiConvert( s ) );
}
return aTmp;
}
if( 0 == objTypeName.IndexOf( "System.Management." ) )
{
Document tmpdoc = null;
switch( objTypeName )
{
case "System.Management.ManagementObject":
case "System.Management.ManagementBaseObject":
tmpdoc = new Document();
ManagementBaseObject mbo = (ManagementBaseObject) obj;
tmpdoc.Add( "WmiPath", mbo.SystemProperties["__PATH"].Value );
tmpdoc.Add( "WmiServer", mbo.SystemProperties["__SERVER"].Value );
AddPropsToDoc( tmpdoc, mbo.Properties );
newObj = tmpdoc;
break;
default:
break;
}
return newObj;
}
return newObj;
}
protected void AddPropsToDoc( Document doc, object obj )
{
foreach ( var propData in (PropertyDataCollection)obj )
{
doc.Add( propData.Name, WmiConvert( propData.Value ) );
}
}
}
Hope this helps.
Labels:
hth,
mongodb,
powershell
Subscribe to:
Posts (Atom)