Home » C# Programming

Powershell Script Output to Windows Form List View


I have a powerscript see below.

 [System.String[]] $PackageBasePath

# Initialize a hash table that stores GUID -> name associations
$Packages = @{}

# Get a list of all .OSD files below the base path passed in
$SFTFiles = Get-ChildItem $PackageBasePath -filter *.osd -force -recurse

# Store each OSD file's data (name and GUID)
foreach ($SFTFile in $SFTFiles)
 # Read the OSD file
 [xml] $SFTFileXML = Get-Content $SFTFile.FullName
 # Store relevant information

 if ($Packages.ContainsKey($PkgGUID) -eq $false)
  $Packages.Add($PkgGUID, $PkgName)

Write-Output "`n============================================================`nDependencies found:`n============================================================`n"

# Process each package's dependencies
foreach ($SFTFile in $SFTFiles)
 # Read the OSD file
 [xml] $SFTFileXML = Get-Content $SFTFile.FullName
 foreach ($PkgDependency in $PkgDependencies)
  # Extract package information (again)
  # Extract the GUID the package depends on
  $PkgDependencyGUID = $PkgDependency.GUID
  # Look up the depending package's name
  if ($PkgDependencyGUID -ne $null -and $Packages.ContainsKey($PkgDependencyGUID))
   Write-Output "$PkgName -> $($Packages.Get_Item($PkgDependencyGUID))"
 #           Export-Clixml -path "c:\ps\test.xml" -inputobject "$PkgName -> $($Packages.Get_Item($PkgDependencyGUID))"

Write-Output "`n============================================================`nAll packages found:`n============================================================"
Write-Output $Packages | format-table -auto @{Label="Name";Expression={$_.Value}},@{Label="GUID";Expression={$_.Name}}

This script will read APP-V OSD files for CODEBASE dependancy and output to screen i.e

Write-Output "$PkgName -> $($Packages.Get_Item($PkgDependencyGUID))"

Now I would like to output this to a windows form control say a listview , please can you advise how I would run the script from C# button and excute the output to a listview control.

Many Thanks Mike.


2 Answers Found


Answer 1

Create a batch file, add your shell script  to it and execute it from C# . See programing details in the below link. Once your program processed, read  the xml  and add the data  to listview  control.

command execution link:


how to read the xml file:


List view  Example:



Answer 2

if you got this result please send the code to me how to populate to listview from prowershell result window

send me code to this mail whoknows1984@hotmail.com


Hello all,
I am trying to itterate through data values in specific columns in a sharepoint doc library.

using the code below I can return the Title fine, however I canno retrieve data for any other user column. Can someone help me understand this behavior and point me to a solution?

$docliburl=”My correct url"
$relweburl=”/correct directory”
[System.Reflection.Assembly]::LoadWithPartialName(”Microsoft.SharePoint”) > $null
$site=new-object Microsoft.SharePoint.SPSite($docliburl)
foreach($list.Items in $list)
$list.Items | select Title,column1,column2

Thanks in advance.


I have a script that builds a list of items.  I'd like to add the ability to download the list items' attachments to a local directory.  IS this possible?  There are lots of examples of how to add attachments but nothing that can download the attachments.  Any help would be appreciated.

I have setup SharePoint 2010 on my Windows 7 x64 box for testing (the basic two button click and it is all configured). I have also created all the PowerShell scripts for installing and configuring SharePoint 2010 on a Windows Server 2008 R2 server. I am using some modifications from the SharePoint Team's SPModule along with my own scripts to start services, create web applications and site collections.

My question is: I would like to create the same configuration from my scripts on my Windows 7 box. Before I remove SharePoint 2010 from my Windows 7 box is there any limitations or modifications that need to made to my scripts before it will allow me to install and configure SharePoint 2010 via PowerShell scripts on  a Windows 7 box?


(SQL Server 2008 Enterprise x64, running under Windows Server 2008 R2 x64)

I have successfuly created a SQL Agent Job step using Powershell to run this code to script all jobs out to a file.  The file gets created just fine; I actually found that using a command shell step that pipes in a script file was necessary to avoid a malformed file. (here is the PowerShell Code):

Powershell Code:

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server"\SQLPROD
$srv.JobServer.Jobs | foreach {$_.Script()} | out-file \\SQLBackups\SQLPROD\failoverscripts\Create_SQL_JOBS.sql

However, when I go to my other server, open a new query window, and execute the Create_SQL_JOBS.sql script to have the jobs recreated, I get tons of errors saying that variables have already been declared - as a result no jobs are created.  (Not having GO in between each job creation section is probably the issue).  This is to be an automated process - manual intervention of adding GO is not an option for me.

Errors (there are many errors, this is as sample set of them:

Msg 134, Level 15, State 1, Line 95
The variable name '@ReturnCode' has already been declared. Variable names must be unique within a query batch or stored procedure.

Msg 134, Level 15, State 1, Line 104
The variable name '@jobId' has already been declared. Variable names must be unique within a query batch or stored procedure.

Msg 132, Level 15, State 1, Line 243
The label 'QuitWithRollback' has already been declared. Label names must be unique within a query batch or stored procedure.

Msg 132, Level 15, State 1, Line 245

The label 'EndSave' has already been declared. Label names must be unique within a query batch or stored procedure.
Msg 134, Level 15, State 1, Line 249

I was expecting something more like how SSMS scripts out mulitple jobs and works just fine.

Can anyone suggest a better way? I am also open to using VBScript in a SQLAgent Step as well. A Nice to have would be something also filters the jobs to script with a condition (JobName Not Like 'AdminJob -%'

Thank you very much for helping me,



I have a display view for parent list.I also add data view for child list on the same display form and filtered the data view on parent list id, below the data view i added a link for Add New Form for child list.I am trying to send a parent Id to the Add new Form for child list using query string but can not get the id of Parent list.

As I noticed that display form does not contain the Id column. is that is the reason i am not getting id ?

is there  any other solution for this?



I have external program (code analyzer) that produce messages like standard C++ compiler into Visual Studio:

c:\file.cpp(10): error T453: text of error

When I use Error List or Output Window to output this message I can use very good navigation. If I click to message then I go to selected line in file. And even file has some changes (for example, in start of file I press Enter twice and needed line is 12 instead 10) navigation works fine.

But I don't want use Error List and Output Window, I want use own window like error list for this messages. And I must implement own navigation mechanism. I can open file and go to needed line number (for example with help IVsTextManager and NavigateToLineAndColumn), but how I can make a navigation if file has a changes (and line number is changed)?


I created a view for my list ,I am filtering the data in this view with the condition of Title is  equal to 'Test1'.Here only the Test1 data is coming and I made this as default view.It is working fine here.

Now I created the XSLT list view webpart and placed that list here.But here all the data is coming in this webpart instead of 'Test1' Data.In the xslt code i checked,there viewname and every thing is fine.

My question is here I need only 'Test1' data i e actual view data.

How can I achive this?



Hi, I get the following error while trying to execute a powershell script.

New-Object : Cannot find type [Microsoft.SQlServer.Management.Sdk.Sfc.SqlStoreConnection]: make sure the assembly containing this type is loaded.

I'm trying to implement policies across different sql server instances from a primary instance. The script can be found @ http://blogs.msdn.com/sqlpbm/archive/2008/06/14/running-against-sql-server-2005-and-sql-server-2000.aspx

Thanks for your help.



I was trying to use the execute process task to kick off a powershell script.  However, nothing happens when I run in debug (the component turns yellow and stays yellow).  Any idea if what I am trying to do is possible and the proper way to configure it?

btw, I am using powershell for the remoting capabilites.  I need to execute a bat file on a remote server which runs a process in a legacy program. 

Update:  When I name the ps1 script file in the executable window, it opens it in notepad.  This would be like the default if you double clicked the file.



Hi there,

I want to write a CLR-Store Procedure (in c#) to run Powershell in SQL Server 2008.

I have followed the msdn pages but struggle for hours. Here is the details:

To use powershell in CLR-Store Procedure, it will need to use System.Management.Automation.dll.

But this DLL isn't not support in the SQL Server, so i manually added by type this in Management Studio,

  CREATE ASSEMBLY [System.Management.Automation] from 'C:\Windows\assembly\GAC_MSIL\System.Management.Automation\\System.Management.Automation.dll' WITH PERMISSION_SET = UNSAFE

After adding a few dependence DLLs, I succeed added the System.Management.Automation.dll.

Then I created a visual C# SQL CLR Database Project and add the System.Management.Automation.dll in the reference, and here is the code in C#:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

public partial class StoredProcedures
    public static void testAssembly()
        Runspace runspace = RunspaceFactory.CreateRunspace();



After I deployed the project into SQL Server, and I run the CLR-Store Procedure (let say testAssembly)

EXEC testAssembly,

But I get the following errors:


Msg 6522, Level 16, State 1, Procedure testAssembly, Line 0
A .NET Framework error occurred during execution of user-defined routine or aggregate "testAssembly":
System.Security.SecurityException: That assembly does not allow partially trusted callers.
   at StoredProcedures.testAssembly()


I have already executed


in my database. I have tried to make the System.Management.Automation.dll to be "SAFE" or "EXTERNAL ACCESS", but it gives errors. I can only set the DLL be "UNSAFE"

Could anyone tell me what is going on? Thanks a lot



I am trying to invoke a powershell script from C#. It works fine.But when i want to send some parameters to the script like "username","Password", the addscript call fails.seems like loading a script failed. i tried addparameter function as well.that doesn't work as well.

what could be the problem.

how to invoke scripts using addscript method and pass parameters to that script for its execution.




I have a Powershell script something like this :

function DoSomething([String]$code, [string]$somemore
   Powershell Calls

I want to call the above from C# and I was wondering if someone can tell me how to ?


Can anybody help me with writing a powershell script to edit contents of a content editor webpart in the home page of all my site collections in the web application.

Thanks in advance,



When updating an InfoPath template (e.g. adding a new field), any views I have created on the library lose their filters and sorting, as if the columns on which they were built no longer exist.  Has anyone else encountered this and, if so, is there a solution?




  I have a Sqlserver 2008 and about 120 Sql Agent jobs. We are planning to create new environments and I need to create the same jobs in all the new environments. Now i can script each job individually and then run them on the new servers but i was wondering if there is a Powershell way of looping though all the jobs and generate scripts for them and put them all in one big Sql, so i can just run that 1 script in any new environments that we add to create all the jobs that we have.


I found the below script online and am trying to make changes to it but cannot find the methods to scripts a existing object


# Load SMO extension

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null;

# Get List of sql servers to check

$sqlservers = Get-Content "$Env:USERPROFILE\sqlservers.txt";


# Loop through each sql server from sqlservers.txt

foreach($sqlserver in $sqlservers)


      # Create an SMO Server object

      $srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver;


      # Jobs counts

      $totalJobCount = $srv.JobServer.Jobs.Count;

      $failedCount = 0;

      $successCount = 0;


      # For each jobs on the server

      foreach($job in $srv.JobServer.Jobs)


            # Default write colour

            $colour = "Green";

            $jobName = $job.Name;

            $jobEnabled = $job.IsEnabled;

            $jobLastRunOutcome = $job.LastRunOutcome;


            # Set write text to red for Failed jobs

            if($jobLastRunOutcome -eq "Failed")


                  $colour = "Red";

                  $failedCount += 1;


            elseif ($jobLastRunOutcome -eq "Succeeded")


                  $successCount += 1;


            Write-Host -ForegroundColor $colour "SERVER = $sqlserver JOB = $jobName ENABLED = $jobEnabled LASTRUN = $jobLastRunOutcome";




      # Writes a summary for each SQL server

      Write-Host -ForegroundColor red "=========================================================================================";

      Write-Host -ForegroundColor red "$sqlserver total jobs = $totalJobCOunt, success count $successCount, failed jobs = $failedCount.";

      Write-Host -ForegroundColor red "=========================================================================================";




Any help greatly appreciated.





Hi Everyone

I posted 12 PowerShell scripts for ADOMD.NET and 9 PowerShell scripts for AMO in the Script Repository:

These 21 scripts provide my PowerShell 2.0 translation of C# code created by the authors of Microsoft SQL Server 2008 Analysis Services Unleashed.  I have tested this code on 64-bit Windows 7 running SQL Server 2008 R2 with Analysis Services, and the Windows PowerShell version 2 IDE (Integrated Development Environment).  This code requires the sample “Food Mart 2008” database (which you may need to copy in as “FoodMart 2005”) available from the authors’ website at http://www.informit.com/store/product.aspx?isbn=0672330016

I shared this code as part of my data mining blog.  I have been reviewing this book by chapter.
I made comments on the ADOMD.NET code at http://www.marktab.net/datamining/index.php/2010/07/22/adomd-net-with-powershell-2-0-and-c-4-0/
I made comments on the Analysis Management Objects (AMO) code at http://www.marktab.net/datamining/index.php/2010/07/26/analysis-management-objects-amo-and-powershell-2-0/

If you are doing administrative tasks with Analysis Services, I recommend using PowerShell instead of .NET Console applications.

Gorbach, I., Berger, A., & Melomed, E. (2009). Microsoft SQL Server 2008 Analysis Services Unleashed. Indianapolis, IN: Pearson Education Inc.

I am retrieving demographic info from a sharepoint list and displaying it in the last name drop down with a dataconnectioon. That works fine. I want to sort of the records being displayed to be in last name order so I created a view over the sharepoint list and used this address in the data connection area. The view list appears to be found ok as I see only the select fields in the view which are less than in the actual list. However, I do not have the correct sort coming in my last name as it is using the original sort on the list. Is this possible to do?
My problem should be fairly simple. I have an external list full of people. That list has related lists, let's say their orders. If you search that list, you can click that person's profile page and it pulls up the correct information. However, if you click on the person's customer number from the list itself, it just brings up the standard view form with only the customer information. Is there a way I can make that link to their profile page, instead of the standard view form full of redundant information?
Has anyone created a PowerShell script to configure variations? If so, can you please share the script?

I've got a powershell script that is executed through a Execute Process Task that is giving me an error when executed through the Execute Package Utility on a 64bit server.

"c:\windows\system32\windowspowershell\v1.0\powershell.exe" ""& 'C:\CubeArchive\Linked DB to XMLA.ps1'"" at "", The process exit code was "1" while the expected was "0".

Here's the rub:

It runs fine from Visual Studio on that server.

On my local maching (32bit), it runs fine from both Visual Studio and Execute package Utility.

Does anyone have any idea why this is happening?





<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure