12 Replies Latest reply on Jun 26, 2017 7:50 AM by capetocairo

    Using Get-Content in Script

    capetocairo

      I am attempting to leverage Powershell to update custom properties of a batch of nodes with no consistent IP schemes. I am fairly new to Powershell, but I have a script working to change custom properties of a single IP. I was hoping I could create a text file and somewhere in the script reference the text file of IPs.

       

      Here's the script:

       

      #Intialization 

      Add-PSSNapin SwisSnapin 

           

      # Connect to SWIS 

      $hostname = "x.x.x.x"

      $username = "username"

      $password = get-content Path\To\PWinfo.txt | convertto-securestring 

      $cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $password 

      $swis = Connect-Swis -host $hostname -cred $cred

           

      # prepare a custom property value 

      $customProps = @{ 

        Address=" "

        ASRN=" "

        AssetTag=" "

        CircuitID=" "

        City=" "

        Comments=" "

        ConfiguredBy=" "

        Department=" "

        ESN=" "

        FourthSiteEmail=" "

        InServiceDate=" "

        PONumber=" "

        PurchaseDate=" "

        PurchasePrice=" "

        Recorder_Type=" "

        SecondarySiteEmail=" "

        SiteEmail=" "

        TertiarySiteEmail=" "

        Tower_Location=" "

           

      # set the custom property 

      $uris = Get-SwisData $swis "SELECT Nodes.CustomProperties.Uri FROM Orion.Nodes WHERE IP_Address LIKE 'x.x.x.x'" 

      $uris | Set-SwisObject $swis -Properties $customProps

       

      Where would I inject the get-content file to be referenced? Thanks in advance!

        • Re: Using Get-Content in Script
          tdanner

          If you have a text file containing one IP address per line and nothing else, you can load the file into a list of strings like this:

           

          $filename = .\my-ips.txt

          $ips = Get-Content $filename

           

          Then you can look up the custom property uris for those IPs like this:

           

          $uris = Get-SwisData $swis "SELECT Nodes.CustomProperties.Uri FROM Orion.Nodes WHERE IP IN @ips" @{ ips = $ips }

           

          And then proceed with updating the custom properties as in the rest of your script.

            • Re: Using Get-Content in Script
              capetocairo

              This throws me an XML error. I have inserted thing things you suggested below:

               

              $filename = "Path\To\File.txt"

              $ips = Get-Content $filename

               

              # prepare a custom property value 

              $customProps = @{ 

                Address=" "

                ASRN=" "

                AssetTag=" "

                CircuitID=" "

                City=" "

                Comments="testing"

                ConfiguredBy=" "

                Department=" "

                ESN=" "

                FourthSiteEmail=" "

                InServiceDate=" "

                PONumber=" "

                PurchaseDate=" "

                PurchasePrice=" "

                Recorder_Type=" "

                SecondarySiteEmail=" "

                SiteEmail=" "

                TertiarySiteEmail=" "

                TEST_KaceNode=" "

                Tower_Location=" "

                   

              # set the custom property 

              $uris = Get-SwisData $swis "SELECT Nodes.CustomProperties.Uri FROM Orion.Nodes WHERE IP IN @ips" @{ ips = $ips }

              $uris | Set-SwisObject $swis -Properties $customProps 

                • Re: Using Get-Content in Script
                  tdanner

                  What XML error?

                    • Re: Using Get-Content in Script
                      capetocairo

                      Get-SwisData : There was an error generating the XML document.

                      At C:\Scripts\DEV\Powershell\TEST-Batch Add Custom Props.ps1:39 char:9

                      + $uris = Get-SwisData $swis "SELECT Nodes.CustomProperties.Uri FROM Or ...

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

                          + CategoryInfo          : NotSpecified: (:) [Get-SwisData], InvalidOperationException

                          + FullyQualifiedErrorId : System.InvalidOperationException,SwisPowerShell.GetSwisData

                       

                      That is the XML error I am getting. The full script with the lines you suggest are below:

                       

                      #Intialization 

                      Add-PSSNapin SwisSnapin 

                           

                      # Connect to SWIS 

                      $hostname = "x.x.x.x"

                      $username = "username"

                      $password = get-content Path\To\PWinfo.txt | convertto-securestring 

                      $cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $password 

                      $swis = Connect-Swis -host $hostname -cred $cred

                       

                      $filename = "Path\To\IPlist.txt"

                      $ips = Get-Content $filename

                       

                      # prepare a custom property value 

                      $customProps = @{ 

                        Address=" "

                        ASRN=" "

                        AssetTag=" "

                        CircuitID=" "

                        City=" "

                        Comments="testing"

                        ConfiguredBy=" "

                        Department=" "

                        ESN=" "

                        FourthSiteEmail=" "

                        InServiceDate=" "

                        PONumber=" "

                        PurchaseDate=" "

                        PurchasePrice=" "

                        Recorder_Type=" "

                        SecondarySiteEmail=" "

                        SiteEmail=" "

                        TertiarySiteEmail=" "

                        TEST_KaceNode=" "

                        Tower_Location=" "

                           

                      # set the custom property 

                      $uris = Get-SwisData $swis "SELECT Nodes.CustomProperties.Uri FROM Orion.Nodes WHERE IP IN @ips" @{ ips = $ips }

                      $uris | Set-SwisObject $swis -Properties $customProps 

                        • Re: Using Get-Content in Script
                          tdanner

                          What is in $ips at this point? It sounds like there may be some problem there.

                           

                          Also, you can use this command to print more information about the most recent powershell error:

                           

                          $error[0]|format-list -force

                            • Re: Using Get-Content in Script
                              capetocairo

                              The file that $ips is calling is just a text document that has two test IPs in it on separate lines.

                               

                              The full PS error is below:

                               

                              Exception         : System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type System.Management.Automation.PSObject was not
                                                  expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
                                                     at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType)
                                                     at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterObjectArray.Write1_Object(String n, String ns, Object o, Boolean isNullable, Boolean needType)
                                                     at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterObjectArray.Write2_ArrayOfAnyType(Object o)
                                                     --- End of inner exception stack trace ---
                                                
                                                  Server stack trace:
                                                     at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
                                                     at SolarWinds.InformationService.Contract2.Serialization.XmlStrippedSerializer.SerializeToStrippedXml(Object value)
                                                     at SolarWinds.InformationService.Contract2.SerializationHelper.Serialize(Object value, String typename)
                                                     at SolarWinds.InformationService.Contract2.PropertyBag.WriteXml(XmlWriter writer)
                                                     at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteIXmlSerializable(XmlWriterDelegator xmlWriter, Object obj, XmlSerializableWriter xmlSerializableWriter)
                                                     at System.Runtime.Serialization.XmlDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
                                                     at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
                                                     at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
                                                     at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
                                                     at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionaryWriter writer, Object graph)
                                                     at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter writer, PartInfo part, Object graph)
                                                     at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameter(XmlDictionaryWriter writer, PartInfo part, Object graph)
                                                     at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameters(XmlDictionaryWriter writer, PartInfo[] parts, Object[] parameters)
                                                     at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter writer, MessageVersion version, String action, MessageDescription
                                                  messageDescription, Object returnValue, Object[] parameters, Boolean isRequest)
                                                     at System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, Object[] parameters, Object returnValue, Boolean
                                                  isRequest)
                                                     at System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
                                                     at System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter writer)
                                                     at System.ServiceModel.Security.SecurityAppliedMessage.OnWriteBodyContents(XmlDictionaryWriter writer)
                                                     at System.ServiceModel.Security.SecurityAppliedMessage.OnWriteMessage(XmlDictionaryWriter writer)
                                                     at System.ServiceModel.Channels.BufferedMessageWriter.WriteMessage(Message message, BufferManager bufferManager, Int32 initialOffset, Int32 maxSizeQuota)
                                                     at System.ServiceModel.Channels.BinaryMessageEncoderFactory.BinaryMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32
                                                  messageOffset)
                                                     at System.ServiceModel.Channels.FramingDuplexSessionChannel.EncodeMessage(Message message)
                                                     at System.ServiceModel.Channels.FramingDuplexSessionChannel.OnSendCore(Message message, TimeSpan timeout)
                                                     at System.ServiceModel.Channels.TransportDuplexSessionChannel.OnSend(Message message, TimeSpan timeout)
                                                     at System.ServiceModel.Channels.OutputChannel.Send(Message message, TimeSpan timeout)
                                                     at System.ServiceModel.Channels.ClientReliableChannelBinder`1.DuplexClientReliableChannelBinder`1.OnSend(TDuplexChannel channel, Message message, TimeSpan timeout)
                                                     at System.ServiceModel.Channels.ReliableChannelBinder`1.Send(Message message, TimeSpan timeout, MaskingMode maskingMode)
                                                     at System.ServiceModel.Channels.ReliableChannelBinder`1.Send(Message message, TimeSpan timeout)
                                                     at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecurityDuplexSessionChannel.Send(Message message, TimeSpan timeout)
                                                     at System.ServiceModel.Dispatcher.DuplexChannelBinder.Request(Message message, TimeSpan timeout)
                                                     at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
                                                     at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
                                                     at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
                                                
                                                  Exception rethrown at [0]:
                                                     at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
                                                     at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
                                                     at SolarWinds.InformationService.Contract2.IInformationService.Query(QueryXmlRequest query)
                                                     at SolarWinds.InformationService.Contract2.InfoServiceProxy.Query(QueryXmlRequest query)
                                                     at SolarWinds.InformationService.InformationServiceClient.InformationServiceCommand.ExecuteReader(CommandBehavior behavior)
                                                     at SwisPowerShell.GetSwisData.ProcessDataReader()
                                                     at SwisPowerShell.GetSwisData.InternalProcessRecord()
                                                     at SwisPowerShell.BaseSwisCmdlet.DoWithExceptionReporting(Action work)
                                                     at SwisPowerShell.BaseSwisCmdlet.ProcessRecord()
                                                     at System.Management.Automation.CommandProcessor.ProcessRecord()
                              TargetObject      :
                              CategoryInfo      : NotSpecified: (:) [Get-SwisData], InvalidOperationException

                              FullyQualifiedErrorId : System.InvalidOperationException,SwisPowerShell.GetSwisData

                              ErrorDetails      :
                              InvocationInfo    : System.Management.Automation.InvocationInfo
                              ScriptStackTrace  : at <ScriptBlock>, C:\Scripts\DEV\Powershell\TEST-Batch Add Custom Props.ps1: line 39

                              PipelineIterationInfo : {}

                              PSMessageDetails  :

                               

                               

                               

                              Get-SwisData : There was an error generating the XML document.

                              At C:\Scripts\DEV\Powershell\TEST-Batch Add Custom Props.ps1:40 char:9

                              + $uris = Get-SwisData $swis "SELECT Nodes.CustomProperties.Uri FROM Or ...

                              +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                              + CategoryInfo      : NotSpecified: (:) [Get-SwisData], InvalidOperationException
                              + FullyQualifiedErrorId : System.InvalidOperationException,SwisPowerShell.GetSwisData
                              • Re: Using Get-Content in Script
                                capetocairo

                                I'm not sure what about the select statement it is not liking. Is there something in the syntax that I am missing?

                        • Re: Using Get-Content in Script
                          capetocairo

                          I'm still getting this same issue. Any guidance would be extremely helpful. Thanks!