Getting started with PowerShellLoopsOperatorsUsing ShouldProcessPowerShell ClassesSwitch statementWorking with ObjectsUsing existing static classesBasic Set OperationsPowerShell FunctionsSending EmailHandling Secrets and CredentialsPowershell RemotingPowerShell "Streams"; Debug, Verbose, Warning, Error, Output and InformationVariables in PowerShellCommunicating with RESTful APIsWorking with the PowerShell pipelinePowerShell Background JobsReturn behavior in PowerShellWorking with XML FilesIntroduction to PsakeUsing the progress barStringsTCP Communication with PowerShellSharePoint ModuleAliasesAutomatic VariablesEnvironment VariablesPowershell profilesEnforcing script prerequisitesUsing the Help SystemSplattingDesired State ConfigurationSigning ScriptsSecurity and CryptographyCSV parsingIntroduction to PesterModules, Scripts and FunctionsPowerShell.exe Command-LineCommon parametersParameter setsRegular ExpressionsPowerShell Dynamic ParametersWMI and CIMGUI in PowershellConditional logicURL Encode/DecodeMongoDBRunning ExecutablesError handlingHashTablesActiveDirectory modulepowershell sql queriesAutomatic Variables - part 2Package managementCmdlet NamingBuilt-in variablesCreating DSC Class-Based ResourcesPowershell ModulesPowerShell WorkflowsHow to download latest artifact from Artifactory using Powershell script (v2.0 or below)?Calculated PropertiesSpecial OperatorsAnonymize IP (v4 and v6) in text file with PowershellComment-based helpAmazon Web Services (AWS) Simple Storage Service (S3)Amazon Web Services (AWS) RekognitionPSScriptAnalyzer - PowerShell Script AnalyzerNaming ConventionsEmbedding Managed Code (C# | VB)Archive ModuleInfrastructure AutomationScheduled tasks moduleISE module

MongoDB

Other topics

Remarks:

The most hard part is to attach a subdocument into the document which hasn't created yet if we need the subdocument need to be in the expected looking we will need to iterate with a for loop the array into a variable and using $doc2.add("Key", "Value") instead using the foreach current array with index. This will make the subdocument in two lines as you can see in the "Tags" = [MongoDB.Bson.BsonDocument] $doc2.

MongoDB with C# driver 1.7 using PowerShell

I need to query all the details from virtual machine and update into the MongoDB.

Which require the output look like this. 
{
    "_id" : ObjectId("5800509f23888a12bccf2347"),
    "ResourceGrp" : "XYZZ-MachineGrp",
    "ProcessTime" : ISODate("2016-10-14T03:27:16.586Z"),
    "SubscriptionName" : "GSS",
    "OS" : "Windows",
    "HostName" : "VM1",
    "IPAddress" : "192.168.22.11",
    "Tags" : {
        "costCenter" : "803344",
        "BusinessUNIT" : "WinEng",
        "MachineRole" : "App",
        "OwnerEmail" : "[email protected]",
        "appSupporter" : "Steve",
        "environment" : "Prod",
        "implementationOwner" : "[email protected]",
        "appSoftware" : "WebServer",
        "Code" : "Gx",
        "WholeOwner" : "[email protected]"
    },
    "SubscriptionID" : "",
    "Status" : "running fine",
    "ResourceGroupName" : "XYZZ-MachineGrp",
    "LocalTime" : "14-10-2016-11:27"
}

I have 3 sets of array in Powershell

        $MachinesList  # Array 
        $ResourceList # Array
        $MachineTags  # Array
    
    pseudo code 

        $mongoDriverPath = 'C:\Program Files (x86)\MongoDB\CSharpDriver 1.7';
        Add-Type -Path "$($mongoDriverPath)\MongoDB.Bson.dll";
        Add-Type -Path "$($mongoDriverPath)\MongoDB.Driver.dll";

 $db = [MongoDB.Driver.MongoDatabase]::Create('mongodb://127.0.0.1:2701/RGrpMachines');
    [System.Collections.ArrayList]$TagList = $vm.tags 
      $A1 = $Taglist.key
      $A2 = $Taglist.value 
    foreach ($Machine in $MachinesList) 
    {
        foreach($Resource in $ResourceList) 
        {
                    $doc2 = $null
                   [MongoDB.Bson.BsonDocument] $doc2 = @{}; #Create a Document here 
                    for($i = 0; $i -lt $TagList.count; $i++)
                           {
                                $A1Key = $A1[$i].ToString()
                                $A2Value = $A2[$i].toString()
                                $doc2.add("$A1Key", "$A2Value")
                           }
                    
                     [MongoDB.Bson.BsonDocument] $doc = @{
                        "_id"= [MongoDB.Bson.ObjectId]::GenerateNewId();
                        "ProcessTime"= [MongoDB.Bson.BsonDateTime] $ProcessTime;
                        "LocalTime" = "$LocalTime";
                        "Tags" = [MongoDB.Bson.BsonDocument] $doc2; 
                        "ResourceGrp" = "$RGName"; 
                        "HostName"= "$VMName";
                        "Status"= "$VMStatus";
                        "IPAddress"= "$IPAddress";
                        "ResourceGroupName"= "$RGName";
                        "SubscriptionName"= "$CurSubName";
                        "SubscriptionID"= "$subid";
                        "OS"= "$OSType";
                    }; #doc loop close
 
                    $collection.Insert($doc);
            }
    }

Contributors

Topic Id: 7438

Example Ids: 24609,24610

This site is not affiliated with any of the contributors.