25 Replies Latest reply on Jul 31, 2018 9:28 AM by gregor

    Gathering of useful PowerShell snippets

      Dear vCampus community,

       

      I was thinking about gathering useful PowerShell snippets similar to Gathering of interesting links at the Generic vCampus Discussions forum. The idea is creating a kind of library over time that can be used to lookup how certain things can be done, is a source for new ideas, raises the interest in performing certain task with Windows PowerShell and also helps resolving certain issues that may occur e.g. in case evaluated permissions are required. This said, I believe we would require separate threads for each certain "How to". I had a discussion with Mathieu Hamel and we believe a new Community Project would fit best.

       

      On the content side I can think of Operating System related tasks, maintaining HyperV machines, PI System administration tasks, links to useful resources and other things that you could think of PowerShell would be a good fit to. Based on my own experience with Windows PowerShell there are a few hurdles that can indeed be a bit frustrating but the more I become used to using PowerShell the more I see its beauty. PowerShell is for sure not the right answer to everything and thus I expect there's a requirement for discussions about where it fits and what alternatives exist. I can also imagine there exist security related concerns e.g. when allowing Remote Management through PowerShell. So we may want to talk about what the risks are and what can be considered good practice.

       

      A community project lives from the activity of the community members. Hence please let us know if you are interested in such a Community Project, if you have experience using Windows PowerShell, if you possibly have already snippets that you would like to share. Please share your thoughts.

        • Re: Gathering of useful PowerShell snippets
          Rick Davin

          I think this is an excellent idea!  Would suggest any submissions should reference PS and/or snap-in version numbers.

            • Re: Gathering of useful PowerShell snippets

              Hello Rick,

               

              Thank you for your support and your suggestion about adding appropriate version information. Microsoft is still enhancing PowerShell functionality and there have been major enhancements between versions in the past. Also not all PowerShell versions are supported on the Operating System platforms that are commonly used these days.

               

              I have a few things on my list that I am looking forward to share. My idea was to also list error messages one may run into, explain their meaning and how to address them. I am hoping for contrary discussions since a solution isn't always the only one and sometimes there are better choices. I am hoping to arouse curiosity with vCampus members that haven't touched PowerShell yet, to make them keen about getting their hands dirty and to provide some guidance good enough to keep folks going on.

               

              All together I am hoping we will be able to through some small stones into the water and see the small waves adding up to bigger and bigger ones.

                • Re: Gathering of useful PowerShell snippets

                  Sounds good to me.

                   

                  Why isn't the PS security tool announced over on community.osisoft.com a community project? Sounds similar to what you are suggesting.

                    • Re: Gathering of useful PowerShell snippets

                      Hello Rhys,

                       

                      Please allow me to refer you to Mathieu's The specified item was not found. post. My understanding is that the Baseline Security tool is intended as community project at the Cyber Security Community forum. The idea is to make this tool available for registered Community users - almost public. This way the audience also includes e.g. PI System Managers that may not have own a vCampus subscription.

                       

                      PI System Baseline Security Tool is designed as a framework that can easily be enhanced but all is related to Operating System and PI System security. What I am thinking of is more general and less focused on security even there will likely be many things that touch security related matters. I like to focus on less complex examples and don't intent to create anything complex. I believe at this point it's a good idea to share what's on my list to share:

                       

                      - How to compact HyperV VHD / VHDX files using PowerShell?
                      - How to maintain Windows Firewall using PowerShell?
                      - How to mount a network share using PowerShell?
                      - How to list information about (PI) processes using PowerShell?
                      - How to stop or restart remote machines using PowerShell?

                       

                      I hope to make people curious enough with one or the other topic to just give it a try and maybe become infected. I wouldn't know why we couldn't discuss one or the other snippet used within PI System Baselining Security Tool.

                        • Re: Gathering of useful PowerShell snippets

                          Here's a snippet then until we have a location for snippets...how to get an OSIsoft installation package, extract it, install it silently and then (simply) validate the installation. Someone could take the concept and run up a more generic method to do the whole process by using parameters; I've stripped & changed this from some big PS scripts. Some older OSIsoft packages use different installers so you need a different approach. This example is for AF SDK 2.5.1. It took some figuring out in the beginning but in hindsight is fairly straightforward.

                           

                           

                           
                          # Some variables
                          $package = "C:\PIAFClient_2012_SP1_.exe"
                          $newTemp = "C:\MyTempPath\"
                          $origTemp = $Env:TEMP 
                          
                          # Control temp directory
                          [environment]::SetEnvironmentVariable("Temp",$newTemp,"User")
                          [environment]::SetEnvironmentVariable("Temp",$newTemp,"Machine")
                          [environment]::SetEnvironmentVariable("Temp",$newTemp,"Process")
                          
                          # Extract
                          Start-Process -FilePath $package -ArgumentList "-nr -y" -Wait 
                          
                          # Activate silent installation - you could just pass silent.ini as an argument.
                          Rename-Item ($newTemp + "AFClient_2.5.1.5159\setup.ini") -NewName "old-setup.ini"
                          Rename-Item ($newTemp + "AFClient_2.5.1.5159\silent.ini") -NewName "setup.ini"
                          
                          # Replace server defaults
                          (Get-Content ($newTemp + "AFClient_2.5.1.5159\setup.ini")) | ForEach-Object { $_ -replace "PI_SERVER=MyServer", "PI_SERVER=RHYSPI" } | Set-Content ($newTemp + "AFClient_2.5.1.5159\setup.ini")
                          # ... some other defaults replaced, omitted for shortness of post
                          
                          # Start installation - should check the extraction has worked but assume it has
                          Start-Process ($newTemp + "AFClient_2.5.1.5159\setup.exe") -ArgumentList ($newTemp + "AFClient_2.5.1.5159\setup.ini") -Wait
                          
                          # Validate installation
                          # Hardcoded paths; I know I should use the registry to find the paths.
                          if ((Test-Path "C:\Program Files (x86)\PIPC\AF\PublicAssemblies\OSIsoft.AFSDK.dll") -eq $true)
                          {
                               [String] $ver = [System.Diagnostics.FileVersionInfo]::GetVersionInfo("C:\Program Files (x86)\PIPC\AF\PublicAssemblies\OSIsoft.AFSDK.dll").FileVersion
                               if ($ver -eq "2.5.1.5159")
                               {
                                    # Seems to have worked so grab a beer, in fact grab 2.
                               }
                          }
                          
                          [environment]::SetEnvironmentVariable("Temp",$origTemp,"User")
                          [environment]::SetEnvironmentVariable("Temp",$origTemp,"Machine")
                          [environment]::SetEnvironmentVariable("Temp",$origTemp,"Process")
                          

                           

                            • Re: Gathering of useful PowerShell snippets

                              Hello Rhys,

                               

                              Thank you for sharing this example. I understand you are pushing and you are right.

                               

                              I was dreaming of a few more positive replies from other users. Turns out a lot less than 1 per thousand of the vCampus community has subscribed to this forum This said, I must be pretty thankful for positive feedback from 50% of the non-OSIsoft email subscribers Thank you Rick & Rhys I owe you a

                               

                              My next action will be a reference to this post at Generic vCampus Discussions. Let's see how this works out.

                               

                              @Rhys: Would you mind creating a new thread for your example at Gathering of useful PowerShell snippets community project forum? As the gentlemen that I am, I like to offer you the opportunity to be the first one  I assume your example requires at least PowerShell 2.0

                               

                              Please don't forget to email-subscribe

                               

                               

                               

                              EDIT: "ppm" replaced with "per thousand" - let's stay realistic 

                                • Re: Gathering of useful PowerShell snippets

                                   

                                   

                                  Here is the script to return records from a query:

                                   
                                  function PIRead-EF {
                                       [CmdletBinding()]
                                       param (
                                            [Parameter(Mandatory=$true)] [string]$AFServer,
                                            [Parameter(Mandatory=$true)] [string]$AFDB,
                                            [Parameter(Mandatory=$true)] [string]$View
                                       )
                                      $ErrorActionPreference = "Stop"
                                       $constring='Provider=PIOLEDBENT.1;User ID="";Initial Catalog='+$AFDB+';Data Source='+$AFServer+';Extended Properties="";Integrated Security=SSPI;Command Timeout=-1;Log Level=0;Log File="";Shorten Primary Keys=False;Always Return Rowset=False;Defer Execution=False;Disable Server Selection=False;Time as Double=False;Optimization Log Limit=100;Keep Default Ordering=False;Embed Errors=False;Ignore Errors=False;Function Errors as NULL=False;Cancel On Low Resources=True;Show Hidden Metadata=False;Allow Expensive=False;Use Agent=True'
                                       $cmd='SELECT * FROM ['+$AFDB+'].[DataT].['+$View+']'
                                       $ef=Get-OLEDBData $constring $cmd
                                       if ($ef -eq $null){
                                            Write-Verbose "0 records returned" 
                                            }
                                       return $ef
                                       }
                                       
                                  function Get-OLEDBData {
                                       [CmdletBinding()]
                                       param ($connectstring, $sql) 
                                          $OLEDBConn = New-Object System.Data.OleDb.OleDbConnection($connectstring)
                                          $OLEDBConn.open()
                                          $readcmd = New-Object system.Data.OleDb.OleDbCommand($sql,$OLEDBConn)
                                          $readcmd.CommandTimeout = '300'
                                          $da = New-Object system.Data.OleDb.OleDbDataAdapter($readcmd)
                                          $dt = New-Object system.Data.datatable
                                          [void]$da.fill($dt)
                                          $OLEDBConn.close()
                                          return $dt
                                  }
                                  

                                   

                                   

                                  And, if you want this exported as CSV, you can pipe the output to the built-in Export-CSV cmdlet.

                                    • Re: Gathering of useful PowerShell snippets

                                      And here is a script to update an AF attribute:

                                       

                                       

                                       
                                      function PIUpdate-AFAttrib{
                                      [CmdletBinding()]
                                           param (
                                                [Parameter(Mandatory=$true)] [string]$AFServer,
                                                [Parameter(Mandatory=$true)] [string]$AFDB,
                                                [Parameter(Mandatory=$true)] [string]$Element,
                                                [Parameter(Mandatory=$true)] [string]$Attribute,
                                                [Parameter(Mandatory=$true)] [string]$Value )
                                      
                                      $ErrorActionPreference = "Stop"
                                      
                                      [System.Reflection.Assembly]::LoadWithPartialName("OSIsoft.AFSDK") | Out-Null
                                      $PISystems=New-object OSIsoft.AF.PISystems
                                      $PISystem=$PISystems.DefaultPISystem
                                      $myAFDB=$PISystem.Databases[$AFDB]
                                      $myElement=$myAFDB.Elements.Item($Element)
                                      $myAttr=$myElement.Attributes.Item($Attribute)
                                      if ($myElement.CheckOut()) {
                                           $myAttr.SetValue($Value)
                                           $myElement.CheckIn()
                                           }
                                      }
                                      

                                       

                                  • Re: Gathering of useful PowerShell snippets
                                    mhalhead

                                    Hi,

                                     

                                    Has anyone looked at using Desired State Configuration (DSC) for the installation of PI software?

                                      • Re: Gathering of useful PowerShell snippets
                                        Marcos Vainer Loeff

                                        Hi Michael,

                                         

                                        Actually this is the first time I have heard about DSC. I have read this interesting article from technet about it. 

                                         

                                        Under the section "Why is DSC so cool?", there are some interesting comments such as: "DSC is designed to support “continuous deployments” which means that you can deploy your configuration over and over without breaking anything".

                                         

                                        I wonder the power of integrating DSC with PowerShell Tools for the PI System. That is a good idea for a blog post for sure!

                                         

                                         

                                          • Re: Gathering of useful PowerShell snippets
                                            epennaz

                                            Hi Michael,

                                             

                                            I’ve set up DSC to monitor a few routine features, but I believe I've only scratched the surface of what’s possible. Grabbing the new DSC resource kit it’s pretty easy to get started with a configuration. For example, this just checks to make sure PI Perfmon is set to automatic start up on your local node:

                                             
                                            #Configuration Script     
                                            Configuration MyServiceConfig
                                            {
                                                Import-DscResource -Name MSFT_xServiceResource -ModuleName xPSDesiredStateConfiguration
                                                
                                                 Node localhost
                                                 {
                                                     xService service
                                                     {
                                                     Name = "PIPerfMon1" # ResourceName 
                                                     StartupType = "Automatic"
                                                     }
                                                 }
                                            }
                                            
                                            #Compile the MOF
                                            MyServiceConfig 
                                            
                                            #Apply the MOF
                                            Start-DscConfiguration -force -verbose -Path "C:\Program Files\WindowsPowerShell\MyServiceConfig\"
                                            

                                            The same types of configuration files could be created to, for example, make sure your AF Client Versions were the same across your PI System (after setting up an IIS pull server) or to make sure your PI Data Archive services are all running.

                                             

                                            I think it would really start to get interesting with a custom resource for the PI System that would enable PI System software configuration. So I’m pretty excited about it and will most likely be experimenting more with it pretty soon. What are your thoughts on use cases? Thanks!

                              • Re: Gathering of useful PowerShell snippets
                                Jerome Lefebvre

                                As an exercise in learning PowerShell, I wrote up a small script that does a find/replace on piconfig script that allows one to have variables in piconfig scripts. I posted it on github at:  https://github.com/JeromeLefebvre/abetterpie/blob/master/abetterpie/abetterpie.ps1   . It is really a minor script though.

                                  • Re: Gathering of useful PowerShell snippets
                                    pthivierge

                                    Hello Jerome,

                                     

                                    I believe that an example that shows how to use your script could be useful.

                                     

                                    And thanks for sharing this with the community

                                      • Re: Gathering of useful PowerShell snippets
                                        Jerome Lefebvre

                                        Hello,

                                         

                                        A quick example. Say you want to generate some quick random data for a tag. You first write a quick piconfig with variable script that can add data:

                                         

                                        1. adddata.txt

                                        @table pisnap

                                        @mode edit, t

                                        @istr tag, time, value

                                        %1, *, %2

                                        @ends

                                         

                                        Then write another PowerShell script which feeds it data.

                                         

                                        $counter = 0

                                        while ($counter -ge 0) {

                                                $counter = $counter + 1

                                                $val = ::Sin($counter/10)

                                                .\abetterpie .\adddata.txt fastsinusoid $val

                                        }

                                         

                                        And I’ve recreated a sinusoid tag. I admit it is the world worst interface, but it has the advantage of being very quick to write.

                                         

                                        Cheers,

                                        Jerome

                                          • Re: Gathering of useful PowerShell snippets
                                            gregor

                                            Hello Jerome,

                                             

                                            It's always appreciated when users share code and I really like your approach using piconfig to update a PI Point with data. I also like your humor (A better pie) but am not able to reproduce your solution. I might be able to figure out what you might be doing where it is not 100% clear but imagine somebody new to PowerShell tries your snippet. Failure and success are important measures we (human beings) use to evaluate if we like something or not. PowerShell is great and has a bright future but there are some basic hurdles to overcome for beginners. Even everything works fine with first exercises and one is not running into any issues e.g. because PowerShell Remoting must be enabled first to allow code to execute, trying the first steps on its own can be .. challenging.

                                            I understand your script is supposed writing into file adddata.txt located in a folder named abetterpie that may exist as a parallel folder to the folder your script is stored to. How do you append the data to adddata.txt? It looks to me as if there's a command missing.

                                            You are calling function Sin() which is returning an error too for me. Would you mind sharing the declaration?

                                            If possible for you can you please provide a bit more guidance?

                                              • Re: Gathering of useful PowerShell snippets
                                                Jerome Lefebvre

                                                Hello Gregor,

                                                 

                                                I tried to fix up my script so that you will be able to run it better. If you go to:

                                                JeromeLefebvre/abetterpie · GitHub

                                                And look in the right column, you should be able to see a link to download a zip file

                                                Expand the zip directory and navigate to it in PowerShell

                                                Something like:

                                                cd "C:\Users\jlefebvre\Downloads\abetterpie-master\abetterpie-master\abetterpie"

                                                 

                                                You will then be able to run the script as:

                                                powershell.exe  -ExecutionPolicy Bypass -File .\randomdata.ps1

                                                 

                                                This will create a tag called fastsinusoid on your system and give it two values.

                                                 

                                                This is not a very nice way to run the script, but the security policy of PowerShell are quite script when you download one from the internet and it seems you need to be explicit about how to handle such a script. If anybody in the board knows how to better deal with this, I'd be quite happy to hear it.

                                                 

                                                As for the issue with sin, do you mean that running the following:

                                                [System.Math]::Sin(1)

                                                in a Power Shell command prompt, does not produce the expected result  ( 0.841470984807897 )?

                                                 

                                                Thank you for your interest in this script, I will try to make sure it becomes useful for any who wants to use it.

                                                  • Re: Gathering of useful PowerShell snippets
                                                    mhamel

                                                    Hi Jerome,

                                                     

                                                    You can change the execution policy to allow non-signed script to execute on your machine. It is preferable if you use instead Set-ExecutionPolicy "RemoteSigned". This only allows locally executed non-signed scripts. Make sure also to unblock the file after downloading it from the Internet.

                                                    I would like to share with you a version of the script that I have used for quite a while to perform piconfig scripts from PowerShell. I am attaching the file directly to this post. I give you two ways to use it.

                                                     

                                                    Method 1

                                                     

                                                    C:\PS>$PIScript = @'
                                                    >>
                                                    >>@syst echo.
                                                    >>@syst echo Member Server Configuration ---------------------------------------------------
                                                    >>@syst echo Name,IsCurrentServer,ServerID,Collective,Description,FQDN,SyncPeriod,Role
                                                    >>@syst echo -------------------------------------------------------------------------------
                                                    >>@table pisys,piserver
                                                    >>@ostr name,iscurrentserver,serverid,collective,description,fqdn,syncperiod,role
                                                    >>@sele name=*
                                                    >>@ends
                                                    >>
                                                    >>'@
                                                    
                                                    C:\PS>.\InvokePIConfigScript.ps1 $PIScript
                                                    

                                                     

                                                    Be careful to utilize the @' and '@ characters around the piconfig script to avoid escaping characters. An empty line must follow the first '@ and another empty line must precede the last '@.

                                                     

                                                    Method 2

                                                     

                                                    C:\PS>$PIScript = Get-Content -Path "c:\myPath\script1.dif" | Out-String
                                                    C:\PS>.\InvokePIConfigScript.ps1 $PIScript
                                                    

                                                     

                                                    The first command consists of reading a file with the piconfig script and generate a string with no carriage return and line feed.

                                                     

                                                    Let me know what do you think.

                                          • Re: Gathering of useful PowerShell snippets
                                            kjillson

                                            Maybe a little late in the game, but this is my (mishmashed) attempt at using Powershell (+AF SDK and SMT 2015 OSIsoft PS tools) along with UFL to make a pseudo UFL connector.  Feel free to laugh, comment, rip up, whatever, but I was just fooling around to try to work with the AF SDK a little.  The use case was that a customer wanted a way to have UFL data also create AF elements from a template.  UFL can automatically create new tags when new assets are added, but I also added two PI Points (one to store the last time the script ran, and one to store all the assets that UFL reads in).  Probably a better way to do that second part (since right now if there are a lot of assets already, this point is still going to store every single one, not just the new ones (i didn't dig too deep into the UFL side, but there may be a way for it to check it there in advance).  Anyways, here goes (realized just now that it may be a little confusing that the AF template and root AF element were called server and servers...i had generalized the example to be a data center that was monitoring servers): 

                                             

                                            $picon = Connect-PIDataArchive -PIDataArchiveMachineName "<PIServerHere>"
                                            
                                            #need to check periodically for new updates to tag UFLAssetNameStore
                                            
                                            $Timenow = Get-Date
                                            $lasttimeChecked = (Get-PIValue -PointName "LastCheckedAFUFLAssets" -Time $Timenow -Connection $picon).Value.ToLocalTime()
                                            $AssetsToCheck = Get-PIValue -PointName "UFLAssetNameStore" -StartTime $lasttimeChecked -EndTime $Timenow -Connection $picon
                                            
                                            
                                            #initialize the AF SDK connection to AF db
                                            
                                            [System.Reflection.Assembly]::LoadWithPartialName("OSIsoft.AFSDK") | Out-Null
                                            $PISystems=New-object OSIsoft.AF.PISystems
                                            $PISystem=$PISystems.DefaultPISystem
                                            $AFDB = "TestUFL"
                                            $myAFDB=$PISystem.Databases[$AFDB]
                                            
                                            $rootpath = "\\<PIServerHere>\TestUFL\Servers"
                                            $rootServerElement = $myAFDB.Elements.Item($rootpath)
                                            $listElementsToAdd = @()
                                            
                                            if ($myAFDB.ElementTemplates.Count -eq 1)
                                                {$AFElemTemplate = $myAFDB.ElementTemplates}
                                            else
                                                {$AFElemTemplate = $myAFDB.ElementTemplates.Item("server")}
                                            
                                            foreach ($asset in $AssetsToCheck)
                                                {
                                                    $elementNameToCheck = $asset.Value
                                                    if ($rootServerElement.Elements.Name.Contains($elementNameToCheck))
                                                    {Write-Host("Element Already Exists")}
                                                    else
                                                    {if ($listElementsToAdd.Contains($elementNameToCheck))
                                                        {Write-Host("Element is already queued to be added")}
                                                        else
                                                        {
                                                            $listElementsToAdd = $listElementsToAdd + $elementNameToCheck
                                                            Write-Host("Element to be queued to be added")
                                                        }
                                                    }
                                                }
                                            
                                            foreach ($element in $listElementsToAdd)
                                                {$rootServerElement.Elements.Add($element,$AFElemTemplate)}
                                            
                                            $myAFDB.CheckIn()
                                            
                                            $PISystem.Disconnect()
                                            
                                            #need to write to the last time checked tag
                                            
                                            $finaltime = Get-Date
                                            Add-PIValue -Connection $picon -PointName "LastCheckedAFUFLAssets" -Value $Timenow -Time $finaltime
                                            
                                              • Re: Gathering of useful PowerShell snippets
                                                gregor

                                                Hello Kendell,

                                                 

                                                We started this as a Community Project with the "old" vCampus platform. When moving to Jive and PI Developers Club in December 2014, content was migrated to the new platform and because Jive has no equivalent for Community Projects, content ended up as a Discussion.

                                                 

                                                Please feel encouraged to continue posting your PowerShell snippets to this discussion. I don't recognize anything bad with that. Alternatively you can create a new Discussion, select a sufficient title for your example and share it there. We are always grateful when PI Geeks share know-how because having an active community for sharing knowledge about PI is what we had and still have in mind. Thank you for sharing

                                              • Re: Gathering of useful PowerShell snippets
                                                Jerome Lefebvre

                                                This code is pretty horrible, but it helped me understand a customer who had ten of thousands of tags that were out of order.

                                                It simply formats the output of piartool -ooo so that it reorganizes the tags by pointsource and id.

                                                 

                                                 

                                                $piserverName = "servername"
                                                $con = Connect-PIDataArchive -PIDataArchiveMachineName $piserverName
                                                [System.Collections.ArrayList]$unique_atr  = @();
                                                [System.Collections.ArrayList]$unique_val  = @();
                                                
                                                $piartoolpath =  [environment]::GetEnvironmentVariable("piserver") + "adm\"
                                                
                                                cd $piartoolpath
                                                
                                                $oooEntries = (.\piartool.exe -ooo |  select -Skip 1)
                                                foreach ($line in $oooEntries) {
                                                    $pos = $line.IndexOf(":")
                                                    $tagName = $line.Substring($pos+1)
                                                    $tag = Get-PIPoint -Attributes pointsource, location1 -Connection $con -Name $tagName
                                                    $a = [System.Tuple]::Create($tag.Attributes[$tag.Attributes.keys[0]][0], $tag.Attributes[$tag.Attributes.keys[0]][1])
                                                    if ($unique_atr -contains $a) {
                                                        $ind = [array]::IndexOf($unique_atr, $a);
                                                        $unique_val[$ind] += 1;
                                                    }
                                                    else {
                                                        [void]$unique_atr.Add($a);
                                                        [void]$unique_val.Add(1);
                                                    }
                                                }
                                                for ($i = 0; $i -lt $unique_atr.Count; $i++) {
                                                    Write-Host "Pointsource" $unique_atr[$i].Item1 "with id" $unique_atr[$i].Item2 "has" $unique_val[$i] "tags with out of order events"
                                                }
                                                
                                                
                                                

                                                 

                                                If I knew how to make use of tuples in Powershell, I could greatly have improved this.

                                                • Re: Gathering of useful PowerShell snippets
                                                  pthivierge

                                                  Let me share this small script with you guys, it is intended to monitor performance counters.  Can be very handy when you want to gather data quickly to compare the behavior of two systems.

                                                   

                                                  When the script has run for the time duration specified in seconds, the .blg file is opened and looks like this.

                                                  Another nice thing is the you can copy the blg file and keep it in your archives, so you can look at the chart at any time for reference.

                                                  2015-10-27 11_40_31-Performance Monitor.png

                                                   

                                                  PerfMonScrtipt.ps1

                                                   

                                                  #Settings
                                                  $timeDuration=10 # in seconds
                                                  $outputFile="c:\temp\PIPerformanceStatistics.blg"
                                                  
                                                  
                                                  #Counters
                                                  $counterNames=@(
                                                      "\PI Archive Subsystem\Events Read/sec";
                                                      "\PI Archive Subsystem\Record Load Time Average";
                                                      "\PI Snapshot Subsystem\Snapshots/sec";
                                                      "\Cache\Copy Read Hits %"; 
                                                      "\PhysicalDisk(*)\% Idle Time";
                                                      "\PhysicalDisk(*)\Disk Write Bytes/sec";
                                                      "\PhysicalDisk(*)\Disk Read Bytes/sec";
                                                      "\PhysicalDisk(*)\Split IO/Sec";
                                                      "\PhysicalDisk(*)\Avg. Disk sec/Read"
                                                      "\PhysicalDisk(*)\Avg. Disk sec/Write"
                                                      "\Processor(_Total)\% Processor Time";
                                                      "\Memory\% Committed Bytes In Use";
                                                      "\Network Interface(*)\Bytes Received/sec"; 
                                                      "\Network Interface(*)\Bytes Sent/sec"; 
                                                      
                                                  )
                                                  
                                                  
                                                  # Get counters and the data
                                                  $perfCounters = (Get-Counter -Counter $counterNames -MaxSample $timeDuration)
                                                  
                                                  
                                                  # export results into a BLG File
                                                  $perfCounters | Export-counter -Path $outputfile -Force -FileFormat "BLG"
                                                  
                                                  
                                                  # Opens the BLG file so you can see the trend with the data
                                                  [System.Diagnostics.Process]::Start($outputFile)
                                                  

                                                   

                                                   

                                                  Hope you like!

                                                   

                                                  Patrice

                                                  • Re: Gathering of useful PowerShell snippets
                                                    stuart.watson

                                                    One liner to get a CSV of Asset Framework Server Counts

                                                     

                                                    $refToMyAssembly = [reflection.assembly]::loadwithpartialname("OSIsoft.AFSDK") ; $vals = $false ; (New-Object OSIsoft.AF.PISystems) | % { Try {$null = $_.Connect(); if ( -not $vals ) { $vals = "Server, " + ( $_.GetObjectCounts($null).Keys -join ", ") + "`n" }; $vals += $_.Name +", "; $vals += (($_.GetObjectCounts($null).Values) -join ", ") + "`n"} Catch{}} ; $vals
                                                    
                                                    • Re: Gathering of useful PowerShell snippets
                                                      TimothyVann

                                                      There are a few re-factoring tasks that I find myself doing frequently.

                                                      1.    Deleting invalid archived values

                                                      2.    Multiplying or Dividing archived values by a factor

                                                      3.    Moving or Copying values from one point to another

                                                      4.    Finding archive values and saving to an excel file

                                                       

                                                      I've created a PowerShell function that does all of these tasks.  It suits my uses well, perhaps it will suite yours.  Please make sure you test it before using it in production.  I have tested it for my system and believe I have all the bugs worked out, but this script is capable of wiping out archived values very quickly if you are not careful.

                                                       

                                                      You specify your server and point selection with -serverName, -source (source PI Point Name) and -destination (destination PI Point Name for copy and move actions).

                                                      You define your selection time with -startTime -endTime and then optionally define value filter criteria such as -eq (equals), -gt (greater than), -lt (less than) and -includeNonNumeric.

                                                      You define your -action find, multiply, divide, copy, move, delete.

                                                      When the program runs it finds the points matching your selection.

                                                      Then writes them to a CSV file before processing.  This can be seen as a safety mechanism or just handy for extracting points.

                                                      If -dangerMode is not active the user sees some status of what was found and what is about to happen and is given the opportunity to accept or decline the changes about to take place.

                                                       

                                                      The code has documentation included so I won't write the full documentation here.

                                                      Let me know what you think or if I need to make changes.

                                                       

                                                      -Tim

                                                       

                                                      p.s. I've included the code as an attachment which may be appropriate since the file is 560 lines long, but how do you put highlighted code inline with the message?

                                                        • Re: Gathering of useful PowerShell snippets
                                                          gregor

                                                          Hi Timothy,

                                                           

                                                          The PI Square Community forums are currently available on a hosted Jive platform which. The basic editor is the default but there is also an advanced editor available through the "Use advanced editor" link. The advanced editor offers systax highlighting via the Insert [>>] button. You need to select the paragraph you want to apply highlighting to before. Always useful is the option to toggle between normal and HTML view e.g. if you cannot manage to get the cursor underneath a paragraph you just applied syntax highlighting to.