 |

|
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.
|
|
|
|

|
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.
|
|
|
|
|

|
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.
|
|
|
|

|
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.
|
|
|
|

|
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...  "
modified 29 Jan '13 - 1:27.
|
|
|
|

|
Hi jpmik,
I try active directory add users by means of a. net exe file, my code is as follows:
PowerShell psExec = PowerShell.Create();
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
|
|
|
|

|
Is there a way that I can export the result in XML? Thanks
|
|
|
|

|
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)
}
|
|
|
|

|
Why not do it by using the 'shutdown' commandline command, it can shutdown a remote or virtual system in a polite way.
|
|
|
|

|
Hi thanks for reply
I'm willing to try everything, but how would this 'shutdown' commandline looks like in code?
thanks in advantage
|
|
|
|
|

|
It would be interesting
run PowerShell scripts in remote machine (using credentials)
run PowerShell scripts file (sample, C:\temp\test1.ps1)
kiquenet.com
|
|
|
|

|
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?
|
|
|
|

|
Hi, please run PS-GetSnapin and look at the result, does it include Microsoft.Sharepoint.Powershell ?
|
|
|
|

|
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.
|
|
|
|

|
You need to provide required parameters for executing 'backup-site' cmdlet. These parameters are 'identity' & 'path'
Backup-SPSite http:
|
|
|
|
|

|
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;
|
|
|
|

|
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
|
|
|
|

|
How to start a service with a powershell script as administrator?
|
|
|
|
|

|
The article provided all that I needed to get started. Thanks!
|
|
|
|

|
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
|
|
|
|

|
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.
|
|
|
|

|
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).
|
|
|
|

|
Thanks, it works for me.
huy
|
|
|
|

|
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.
|
|
|
|

|
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.
|
|
|
|

|
How will this work in case the scripts outputs warnings?
|
|
|
|

|
Try using Write-Output. This worked for me.
|
|
|
|

|
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
|
|
|
|

|
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
|
|
|
|

|
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
|
|
|
|

|
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
|
|
|
|
|

|
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?
|
|
|
|

|
Anyone got the solution? I need to use powershell 1 remotely as well. Please post it if you guys here have any good ideas.
|
|
|
|

|
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
|
|
|
|

|
I wrote a script that can do it, I'll post it when I dig it up again
|
|
|
|

|
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
|
|
|
|

|
any script about it ?
kiquenet.com
|
|
|
|

|
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
|
|
|
|

|
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
|
|
|
|

|
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.
|
|
|
|

|
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
|
|
|
|

|
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()
|
|
|
|
|
 |