Click here to Skip to main content
Click here to Skip to main content

How to run PowerShell scripts from C#

By , 29 Aug 2008
 

Screenshot - HowToRunPowerShell_Screen.png

Introduction

This article contains a bare-bones sample on how to add PowerShell scripting to your C# programs. To paraphrase that movie: "the Power of Shell compels you!"

Background

With the release of Windows PowerShell 1.0 in November 2006, we finally have a powerful command line shell for Windows, one that rivals or even exceeds the capabilities of the common Unix/Linux shells such as csh and bash. The reason for this is that PowerShell commands can read and write objects, as opposed to conventional shells that can only process strings of text. Because PowerShell runs on the .NET platform, the objects that are used are .NET objects, which makes it an ideal scripting language for .NET programs.

Prerequisites

Before you can compile the sample code, you'll need a couple of things. First of all, you have to install PowerShell itself, of course, which you can find at the following location: PowerShell homepage. The sample program also references some assemblies that aren't included with the standard PowerShell installation, so you'll have to get those by installing the Windows SDK for Windows Server 2008 and .NET Framework 3.5. Don't worry: even though the latter has 'Server 2008' in its name, it will also install on Vista and XP.

Using the Code

To add PowerShell scripting to your program, you first have to add a reference to the System.Management.Automation assembly. The SDK installs this assembly in the C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0 directory.

Then, you have to add the following 'using' statements to import the required types:

using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

The following code block shows the RunScript method that does all the hard work. It takes the script text, executes it, and returns the result as a string.

private string RunScript(string scriptText)
{
    // create Powershell runspace

    Runspace runspace = RunspaceFactory.CreateRunspace();

    // open it

    runspace.Open();

    // create a pipeline and feed it the script text

    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(scriptText);

    // add an extra command to transform the script
    // output objects into nicely formatted strings

    // remove this line to get the actual objects
    // that the script returns. For example, the script

    // "Get-Process" returns a collection
    // of System.Diagnostics.Process instances.

    pipeline.Commands.Add("Out-String");

    // execute the script

    Collection<psobject /> results = pipeline.Invoke();

    // close the runspace

    runspace.Close();

    // convert the script result into a single string

    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject obj in results)
    {
        stringBuilder.AppendLine(obj.ToString());
    }

    return stringBuilder.ToString();
}

How to Let the Script Interact with your Program

Before executing the script using the pipeline.Invoke() call, it's possible to expose the objects of your program to the script by using the method runspace.SessionStateProxy.SetVariable("someName", someObject). This will create a named variable that the script can access (getting/setting properties, and even calling methods). As an example, suppose we would expose the main form of the sample to the script by adding the SetVariable() call like this:

...
// open it

runspace.Open();
runspace.SessionStateProxy.SetVariable("DemoForm", this);
....

Then, the following script would print the caption of the window:

$DemoForm.Text

The following script would show all the properties and methods of the window:

$DemoForm | Get-Member

Please note, however, that any calls a script makes to your objects will be from another thread context, as pipeline.Invoke() seems to start its own worker thread. This means that your exposed objects will have to be thread-safe.

Points of Interest

As an extra feature, I added the ability to drag-n-drop a script on the form, so you don't have to copy-paste PowerShell scripts into the textbox all the time.

More Information on PowerShell

History

  • Apr 01, 2007: First release
  • Apr 04, 2007: Minor update
  • Aug 28, 2008: Fixed the broken link to the SDK, and the broken link to my second powershell article

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

jpmik
Architect
Netherlands Netherlands
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionCredential error with a complex scriptmemberaSnoussi1 May '13 - 1:33 
I used "Import-Module" to import a script solving the credential problems that I was facing to copy a file from a machine to a remote machine. The following code worked correctly in PowerShell command but while using it with this C# code it gives that error. Any help please ?! I am new with PowerShell.
 
Import-Module -Name C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\Impersonation\Impersonation.psm1
$cred = Get-Credential
Push-ImpersonationContext $cred
Copy-Item C:\Users\guest6\Desktop\SetupConfig2.exe \\amitm-PC\c$\
Pop-ImpersonationContext
 
Error in script : Cannot process command because of one or more missing mandatory parameters: Credential.
QuestionHow to execute Hyper-V Powershell Cmdlets command (GET-VM) in Windows Server 2012 using VS2010 C#??memberAlok Kumar Sharma1 Apr '13 - 11:45 
I have used these code:-
 
private string RunScriptNew()
{
PowerShell ps;
ps = PowerShell.Create();
// Add the PowerShell script to be run
ps.AddScript("GET-VM");
ps.Commands.AddCommand("Out-String");
// execute the script
Collection results = ps.Invoke();
StringBuilder stringBuilder = new StringBuilder();
// convert the script result into a single string
foreach (PSObject obj in results)
{
 
stringBuilder.Append(obj.ToString());
 
}
 
// convert the erros into a single string
 
foreach (ErrorRecord error in ps.Streams.Error)
{
stringBuilder.Append(error.ToString());
}
return (string)
 
}
 
Error:-The term 'GET-VM' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
AnswerRe: How to execute Hyper-V Powershell Cmdlets command (GET-VM) in Windows Server 2012 using VS2010 C#??memberjpmik2 Apr '13 - 10:39 
You probably have to add "Add-PSSnapin -Name Microsoft.SystemCenter.VirtualMachineManager" or "Import-Module virtualmachinemanager" to your script.
 
Please look here for more information:
 
Look here: http://stackoverflow.com/questions/14435177/how-to-run-get-vm-command-on-windows-powershell[^]
QuestionApplication hangs if I run .cmd scriptmemberMember 167164322 Feb '13 - 18:03 
Thanks for publishing this application, it was very helpful.
 
Following is how this script looks like:
 
test.cmd:-
 
@IF "%ECHO%" == "" ECHO OFF
setlocal
set ########
 
call ################.cmd
 
call ################.cmd
 
@echo **** Loading ####### in Powershell *
powershell -sta -noexit "& {;write-host -foregroundcolor green "##### Powershell modules..."; Get-ChildItem -path $env####-Recurse -Filter *.###|%%{if ($env:ARG1 -eq '"-message'") {write-output "importing module $_.fullname"}; ############### Write-IntroMessage}" ***
 
My problem is that when I run the above script, application never returns and hangs for ever. The above script is actually spawning separate powershell.exe and waiting for it close/exit. I was able to reproduce the issue even with the simple following script:
 
test.cmd
 
powershell.exe
 
As far as I know, any .net windows/console application just acts as a host for powershell engine(not really spawns powershell.exe) where we can execute any powershell command or script. But in my day-to-day work, we do use scripts like above in addition to just running the commands. I tried other samples from codeproject like AyncPowerShell and was able reproduce the issue.
 
I'm really stuck here. Do I need to use RunSpacePool? I just started powershell programming so I'm not familiar with all the concepts of it. I think I'm missing something very basic.
 
Thanks in advance,
Ravi.
QuestionPowerShell scripts from C# Failed while runing "Get-Content -Wait C:\TEMP\producer.txt"memberYuri Shterenberg2 Feb '13 - 23:23 
Your application freezing while executing Get-Content -Wait "c:\temp\producer.txt"
I looking for some solution to execute this command "Get-Content -Wait".
And listen to output data and then return control to C# to process the data.
and back again to powershell session.
GeneralSimple typos or fix in code [modified]memberrama charan28 Jan '13 - 19:02 
Thanks a lot for the article .
 
Simple typos or fix in code
1)Path for automation dll in Win7 is
C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0
 
2)replace typo fix
  Collection<psobject /> results = pipeline.Invoke();
with 
  Collection<PSObject> results = pipeline.Invoke();
Hope this helps
Rama Charan Prasad
 
"Be happy and Keep smiling...Smile | :) "


modified 29 Jan '13 - 1:27.

Questionhow to add ad user from sql tablememberocean_blue421 Sep '12 - 0:18 
Hi jpmik,
 
I try active directory add users by means of a. net exe file, my code is as follows:
PowerShell psExec = PowerShell.Create();
 
            //System.Security.SecureString paswrd = new System.Security.SecureString();
            
 
            string command1 = @"$credential = Get-Credential -Credential domainname\Administrator";
            string command2 = @"connect-QADService -service '192.168.1.18'-Credential $credential ";
            string command3 = @"New-QADUser -name '" + FirstName + " " + LastName + "' -ParentContainer 'CN=Users,DC=SRV-TESTDOOS-01' -FirstName  '" + FirstName + "' -LastName  '" + LastName + "' -DisplayName  '" + LastName + " " + FirstName + "' -Description  '" + Description + "' -samAccountName  '" + LastName + ", " + FirstName + "' -Office  '" + Office + "' -Initials  '" + Initials + "' -UserPassword  'p@55w0rd'" + " -HomePhone  '" + TelephoneNumber + "' -WebPage '" + Website + "' -StreetAddress  '" + Street + "' -PostOfficeBox  '" + POBox + "' -City  '" + City + "' -PostalCode  '" + PostalCode + "' -MobilePhone  '" + Mobile + "' -Fax  '" + Fax + "' -Title  '" + JobTitle + "' -Department  '" + Department + "' -Company  '" + Company + "'" ;
            string command4 = @"disconnect-QADService";
			
			
	    psExec.Commands.AddScript(command1);
            psExec.Commands.AddScript(command2);
            psExec.Commands.AddScript(command3);
            psExec.Commands.AddScript(command4);
            
            psExec.Invoke();
 
the. exe file works without error, but otherwise does not happen, I mean no new user added.
any idea how I can fix this?
Thanks
QuestionXML Exportingmembervipfangirl11 Sep '12 - 22:57 
Is there a way that I can export the result in XML? Thanks
QuestionScheduled ShutdownVMGuest_Taskmembertrobolan21 Aug '12 - 2:21 
Hi all
Im pretty new in powershell script, so this might be an odd question, but here we go: I'm writing a ASP.Net site which includes PowerShell script code in the C# methods.. the site is ment to perform PowerOn operations and scheduled shutdownGuest operations on Virtual machines.. I need this to be done from the C#/Script code and not in the VM Client.. I can only find the PowerOff_Task which is the bad way to shutdown VMs.. I need this PowerOff word replaced with some Shutdown-VM_Task thing.. but cant find any.. not possible? I've posted the Scheduled PowerOff script code
 
#Add-PSSnapin VMware.VimAutomation.Core
 
$VIServer = Connect-VIserver -Server server-Protocol https -User user-Password password
 
$VMs = Get-View -ViewType VirtualMachine -Filter @{"Name" = "Gameserver*"}
 
$timestart = (Get-Date).addminutes(5)
 
foreach($vm in $VMs){
 
 $ma = New-Object VMware.Vim.MethodAction
 $ma.Argument = $null
 $ma.Name = "PowerOffVM_Task"
 
 $ots = New-Object VMware.Vim.OnceTaskScheduler
 $ots.runat = $timestart
 
 $spec = New-Object VMware.Vim.ScheduledTaskSpec
 $spec.Name = "Shut Down Guest"# + $VM.name
 $spec.Description = "Shut Down Guest " + $VM.name
 $spec.Enabled = $true
 $spec.Notification = "p.mikkelsen81@gmail.com"
 $spec.Action = $ma
 $spec.Scheduler = $ots
 
 $si = Get-View ServiceInstance
 $stm = Get-View $si.Content.ScheduledTaskManager
 $stm.CreateScheduledTask($vm.MoRef,$Spec)
}

AnswerRe: Scheduled ShutdownVMGuest_Taskmemberjpmik23 Aug '12 - 5:41 
Why not do it by using the 'shutdown' commandline command, it can shutdown a remote or virtual system in a polite way.
GeneralRe: Scheduled ShutdownVMGuest_Taskmembertrobolan23 Aug '12 - 20:18 
Hi thanks for reply
 
I'm willing to try everything, but how would this 'shutdown' commandline looks like in code?
 
thanks in advantage
GeneralMy vote of 4memberBurak Tunçbilek29 Jul '12 - 11:59 
thank you
Questionimprovementsmemberkiquenet.com24 May '12 - 23:33 
It would be interesting
 
run PowerShell scripts in remote machine (using credentials)
 
run PowerShell scripts file (sample, C:\temp\test1.ps1)
kiquenet.com

QuestionCan not run backup scriptmemberaugustwind21 Apr '12 - 5:50 
I converted this code to run with Visual Studio 2010 and mostly, it runs just perfectly.
 
However, trying to run a backup-spsite powershell command (which will work just as expected within PowerShell) I get this error:
 
Error in script : The term 'backup-spsite' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
 
Naturally, 'backup-spsite' is a definite SharePoint powerShell command. The SharePoint module is getting loaded, because other scripts work just fine.
 
Any ideas on how to modify this code so it will run?
AnswerRe: Can not run backup scriptmemberjpmik21 Apr '12 - 8:00 
Hi, please run PS-GetSnapin and look at the result, does it include Microsoft.Sharepoint.Powershell ?
GeneralRe: Can not run backup script [modified]memberaugustwind21 Apr '12 - 12:44 
there's a line I put in before the addscript to run the script in the Runscript method:
pipeline.Commands.AddScript("add-pssnapin microsoft.sharepoint.powershell");
 
it runs that, then it runs the the backup script in the textbox, that I put in. The error is at this line:
 
Collection results = pipeline.Invoke();
 
When it all runs, that's when I get the error - - I've run other SharePoint commands and it runs just fine

modified 22 Apr '12 - 1:25.

AnswerRe: Can not run backup scriptmemberBh@nu4 Jul '12 - 20:52 
You need to provide required parameters for executing 'backup-site' cmdlet. These parameters are 'identity' & 'path'
Backup-SPSite http://server_name/sites/site_name -Path C:\Backup\site_name.bak

GeneralMy vote of 5memberRayler21 Mar '12 - 0:51 
Very helpful!!!
QuestionCannot process command because of one or more missing mandatory parameters: ComputerName.memberJeremyProg122 Nov '11 - 10:22 
I am getting this error when using the code pasted below:
Cannot process command because of one or more missing mandatory parameters: ComputerName.
 
Basically it looks like my additional parameters are not being added to the psscript? Need help sorting out how to do that.
 
My Test-connection.ps1 contains this: "Test-Connection "
 
do I need to pass some parameters in?
 
psScript = "Test-Connection.ps1";
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open runspace
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
 
Command myCommand = new Command(psScript);
CommandParameter testparam = new CommandParameter("ComputerName", ServerName);
myCommand.Parameters.Add(testparam);
pipeline.Commands.Add(myCommand);
 
Collection results = pipeline.Invoke();
 
// close the runspace
runspace.Close();
 
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
 
string psresults = stringBuilder.ToString();
txtResults.Text = psresults;
Questionremotely access the servermemberAbsials16 Nov '11 - 19:59 
hi jpmik,
Nice article. I am wondering if i can update the code to remotely execute the powershell commands for a Lync server. Can u please help me now?
Thanks in advance.
Regards,
ABSIALS
ABSIALS

QuestionStart Service as an AdministratormemberGustavo Eduardo Mendoza Ramirez1 Sep '11 - 9:38 
How to start a service with a powershell script as administrator?
GeneralHere's posting that extends this example a bit...memberrlrcstr23 Aug '10 - 3:32 
Digital Camel - Interacting with PowerShell from C#[^] Big Grin | :-D
GeneralMy vote of 5memberScott Munro12 Aug '10 - 21:30 
The article provided all that I needed to get started. Thanks!
GeneralThe article is great, but I need some help [modified]memberKevin Stock (Atempo)5 Mar '10 - 3:31 
Hi. Thanks for this article, which was very helpful.
 
My problem is that I need a mechanism to call Powershell from C++, so I've encapsulated your example in a library and created the interfaces. Scripts which only use standard Powershell commands work fine, but snap-ins don't seem to be loaded correctly.
 
For example, these two lines:
 
Add-PSSnapin Microsoft.SystemCenter.VirtualMachineManager
Get-PSSnapin
 
work fine in your sample, but in mine, the VirtualMachineManager snap-in doesn't get loaded. There is no error message.
 
In fact, Get-PSSnapin -registered doesn't list the snap-in, even though it is registered and available to your sample.
 
Do you have any suggestions as to what I should look at?
modified on Friday, March 5, 2010 10:30 AM

GeneralRe: The article is great, but I need some helpmemberjpmik5 Mar '10 - 5:21 
Hi Kevin,
 
Is it possible for you to try my asynchronous version of the powershell helper, see Asynchronously Execute PowerShell Scripts from C#[^]. It has better provisions for error handling. Are you using managed or unmanaged C++ ? I suspect your problems are related to code access security, i.e. your C++ process by default doesn't have the rights needed to load snap-ins.
GeneralRe: The article is great, but I need some helpmemberKevin Stock (Atempo)7 Mar '10 - 20:38 
Hi jpmik,
 
Thanks for your reply. I'll let you know how I get on with the asynchronous version; I started with this one for simplicity.
 
I'm using unmanaged C++, as this has to integrate with an existing project, but if necessary I could insert a managed layer between the two. Alternatively (perhaps the simplest) is there a mechanism to give the process the required rights. (Forgive me, I'm not familiar with managed code and all that it involves).
GeneralCoolmemberchunhatbuon198422 Dec '09 - 7:25 
Thanks, it works for me.
 
huy

GeneralNot workingmemberOlegGelezcov6 Sep '09 - 0:13 
Example:
 
$aryService = "EventSystem", "RpcSs"
foreach($strService in $aryService)
{
Write-Host "Service info for: $strService";
Get-Service -Name $strService | fl *
}
 
Output:
Error in script : Cannot invoke this function because the current host does not implement it.
GeneralRe: Not workingmemberJean-Paul Mikkers18 Nov '09 - 8:54 
My example only fetches the output that gets written to the powershell pipeline, it does not implement a PSHost (that would normally be the console window). So if you remove Write-Host from your script it will probably work.
GeneralRe: Not workingmemberMember 769978628 Feb '11 - 8:56 
How will this work in case the scripts outputs warnings?
GeneralRe: Not workingmembershaanr18 Jul '12 - 3:51 
Try using Write-Output. This worked for me.
GeneralCode not workingmemberdeepak_int26 Mar '09 - 18:25 
Dear Jean-Paul Mikkers
 
I m trying to run the following code on Exchange Server 2007:
 
private bool fncCreateForwarding(string ruleName, string recipientEmaillID, string forwardingEmailID)
{
/*
* New-JournalRule -Name "Discovery Journal Recipients" -Recipient
* discovery@contoso.com -JournalEmailAddress "Journal Mailbox"
* -Scope Global -Enabled $True
*/
bool _created = false;
try
{
string _command = string.Empty;
_command = "New-JournalRule";
string _result = string.Empty;
Runspace myRunspace = RunspaceFactory.CreateRunspace();
myRunspace.Open();
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException);
Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);
myRunSpace.Open();
Pipeline pipeLineEnable = myRunSpace.CreatePipeline();
Command myCommand = new Command(_command);
myCommand.Parameters.Add("Name", ruleName);
myCommand.Parameters.Add("Recipient", recipientEmaillID);
myCommand.Parameters.Add("JournalEmailAddress", forwardingEmailID);
myCommand.Parameters.Add("Scope", "Global");
myCommand.Parameters.Add("Enabled", true);
pipeLineEnable.Commands.Add(myCommand);
Collection commandResults = pipeLineEnable.Invoke();
_created = true;
}
catch (Exception ex)
{
Logger.LogError(ex);
}
return _created;
}

 
The problem is that nothing is happening. The code executes without throwing any exception. But the Journaling Rule does not get created. Although when I run the command via Exchange Management Shell the command executes and creates Journaling rule.
 
I would also like to tell that the same code is running perfectly on the other exchange server, but not on the Production server.
 
What can be the problem?
 
Warm regards
Deepak Sharma

GeneralRe: Code not workingmemberdeepak_int31 Mar '09 - 20:03 
I sorted out the problem.
 
The problem was of Application Pool in IIS, I created a separate pool and gave the Administrator user credentials.
 
Thats it
QuestionHow to run more complex scriptsmemberKressilac30 Jan '09 - 9:46 
I'm trying to run the following script from a WCF service. It works much like your code here. Both this application and the one I have written suffer from the same problem in that it doesn't recognize anything but one liner scripts. If you try and execute this inside of Exchange's Powershell command line, everything works perfectly fine. If you try and execute this from inside your application and my WCF service, you get an err: "You cannot call a method on a null-valued expression." which happens on line "$edbfilepath = $objItem.edbfilepath" because the value $db is null. I'm not sure what has to happen with parsing of complex scripts or if nested pipelines are required to get this script to execute but the Powershell Console application is doing something that the API doesn't do by default. There seems to be nowhere else on the web to find even the beginning of the answer because all of the examples use simple "Hello World" scripts instead of real world examples. I was wondering if you ran into anything on the web and might be able to point me in the right direction? Thanks for your help.
 
Add-PSSnapIn microsoft.exchange.management.powershell.admin
$exchangeservers = Get-MailboxServer
$Jumbo = 1024 * 1024
$AllServers = @()
foreach ($server in $exchangeservers)
{
$db = Get-MailboxDatabase -Status -server $server
foreach ($objItem in $db)
{
$edbfilepath = $objItem.edbfilepath
$path = "`\`\" + $server + "`\" + $objItem.EdbFilePath.DriveName.Remove(1).ToString() + "$"+ $objItem.EdbFilePath.PathName.Remove(0,2)
$dbsize = Get-ChildItem $path

$DiskObj = get-WmiObject Win32_LogicalDisk -computerName $server | Where-Object { $_.DriveType -eq 3 -and $_.DeviceID -ieq $objItem.EdbFilePath.DriveName}
$FreeOnStorage = [int]($DiskObj.freespace / $Jumbo)
$FreeOnStorageProc = [float](($DiskObj.freespace /$Jumbo) / ($DiskObj.size / $Jumbo))
 
$start = $path.LastIndexOf('\')
$dbpath = $path.Substring($start +1).remove($path.Substring($start +1).length -4)
$mailboxpath = "$server\$dbpath"
$mailboxcount = Get-MailboxStatistics -database "$mailboxpath" |measure-object
$ReturnedObj = New-Object PSObject
$ReturnedObj | Add-Member NoteProperty -Name "Server\StorageGroup\Database" -Value $objItem.Identity
$ReturnedObj | Add-Member NoteProperty -Name "Size (MB)" -Value ("{0}" -f ($dbsize.Length/1024KB))
$ReturnedObj | Add-Member NoteProperty -Name "Mailbox Count" -Value $mailboxcount.count
$ReturnedObj | Add-Member NoteProperty -Name "LastFullBackup" -Value $objItem.LastFullBackup
$ReturnedObj | Add-Member NoteProperty -Name "LastIncrementalBackup" -Value $objItem.LastIncrementalBackup
$ReturnedObj | Add-Member NoteProperty -Name "BackupInProgess" -Value $objItem.BackupInProgess
$ReturnedObj | Add-Member NoteProperty -Name "Mounted" -Value $objItem.Mounted
$ReturnedObj | Add-Member NoteProperty -Name "IssueWarningQuota" -Value $objItem.IssueWarningQuota
$ReturnedObj | Add-Member NoteProperty -Name "ProhibitSendQuota" -Value $objItem.ProhibitSendQuota
$ReturnedObj | Add-Member NoteProperty -Name "ProhibitSendReceiveQuota" -Value $objItem.ProhibitSendReceiveQuota
$ReturnedObj | Add-Member NoteProperty -Name "MailboxRetention" -Value $objItem.MailboxRetention
$ReturnedObj | Add-Member NoteProperty -Name "FreeOnStorage" -Value $FreeOnStorage
$ReturnedObj | Add-Member NoteProperty -Name "FreeOnStorageProc" -Value $FreeOnStorageProc
$AllServers += $ReturnedObj
}
}
 
$AllServers
QuestionRe: How to run more complex scriptsmemberMember 83770974 Nov '11 - 18:20 
Hi,
 
Did u get a solution to execute the above code without providing username and password?
 
And also I am getting a error when i execute a command which has assignment operator (=)
 
Powershell command: $objUsr= ADSI”LDAP:\\”
 
Error message is : Assignment statements cannot be used in restricted mode.
 
Can you pls help me.. Its urgent
 
Thanks,
Viky Arora
AnswerRe: How to run more complex scriptsmemberjpmik5 Nov '11 - 23:28 
Hi Rakesh,
This looks relevant to your problem:
 
http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2011/08/22/get-full-control-over-your-exchange-remote-powershell-session.aspx[^]
GeneralRemote execute poweshell scriptmemberSam S.25 Mar '08 - 2:54 
Is it also possible to remotely execute scripts in powershell 1? (when you have the credentials of the other machine)
I did not found any info or examples about this yet.
Or will I have to use the CTP of powershell 2.0?
GeneralRe: Remote execute poweshell scriptmemberJulia10055 Dec '08 - 5:21 
Anyone got the solution? I need to use powershell 1 remotely as well. Please post it if you guys here have any good ideas.
GeneralRe: Remote execute poweshell scriptmemberBarron Gillon5 Jan '09 - 9:26 
I seem to remember reading that you cannot remote-execute powershell scripts. You can run WMI queries on remote machines, but that is a service provided by WMI, not powershell
GeneralRe: Remote execute poweshell scriptmemberArrow0fDarkness24 Dec '09 - 17:20 
I wrote a script that can do it, I'll post it when I dig it up again
GeneralRe: Remote execute poweshell scriptmemberAbsials16 Nov '11 - 20:02 
hi,
did u end up with the script to remotely execute the powershell commands?
I shall be very thankful to u for your help.
Regards,
ABSIALS

GeneralRe: Remote execute poweshell scriptmemberkiquenet.com24 May '12 - 23:27 
any script about it ?
kiquenet.com

QuestionHow to pass parameters into the Scripts?memberigormoochnick8 Feb '08 - 15:26 
If I populate the pipeline's input by calling pipeline.Input.Write and then call pipeline.Invoke, how do I reference these parameters from the submiited PS commands or scripts?
 
IM

QuestionPublishing Methodsmembercbruun1 Aug '07 - 23:17 
Hi
 
You can publish variables to be seen from the called PS script using
 
runspace.SessionStateProxy.SetVariable("DemoForm", this);
 
Is there a similar way to publish methods/functions in the C# code to be called from the called PS script ?
 
Thanks
Claus
AnswerRe: Publishing MethodsmemberJean-Paul Mikkers2 Aug '07 - 4:21 
Hi cbruun,
 
Yes, in fact the code you copied does exactly that.. the variable you publish to your PS script is actually a full fledged object, and you can call any public method or property from this object in the PS script.
 
For production code I would advise against indiscriminantly publishing your C# objects to the PS scripts (someone might be tempted to call public methods that weren't meant for 'scripted' consumption). It is better to collect the methods you really want to publish in an interface, and publish an object that implements this interface to the script. In design-pattern-speak: create an Adapter for publication to your PS script.

GeneralRe: Publishing Methodsmembercbruun2 Aug '07 - 11:17 
Thanks for the answer.
 
I was actually considering if this was possible but how does PS get to the parameters ? Reflection ?
 
What if I want to add functions from the C# layer to be functions in PS layer do I then need to use the cmdlet process/model ?
 
And I agree on the isolation of methods...
 
Claus
GeneralRe: Publishing MethodsmemberJean-Paul Mikkers5 Aug '07 - 2:50 

1st: Yep it uses reflection to find the best matching method signature.
2nd: yes that would be the way to go. It seems (allthough I havn't tried this) you can add CmdLets on the fly using runspace.RunspaceConfiguration.Cmdlets.Append()
 

GeneralWhere to find the SDKmemberS. Owens3 Apr '07 - 9:53 
I had an unusual amount of trouble finding the SDK, which is required to get all the assembly goodies. Here's where I found it:
 
http://www.microsoft.com/downloads/details.aspx?FamilyId=C2B1E300-F358-4523-B479-F53D234CDCCF&displaylang=en[^]
 
It says "Vista", but it also installs on XP.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 29 Aug 2008
Article Copyright 2007 by jpmik
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid