[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 446
  • Last Modified:

Import-CSV nt recognized

I have a ps1 script to create mailboxes from a csv file. When I run the ps1 from the powershell commandline, it works fine. But when I call the same script through C# managed code, it bombs with the error message "import-csv" is not a valid cmdlet, script, etc. The same code works fine if I run a ps1 with something simple like get-mailbox or get-organization inside the ps1 file
Import-CSV $path |
foreach {
$Password = convertto-securestring "xxxxxxx" -asplaintext -force
$ln = $_.Lastname.length
if($ln -gt 0)
$name = $_.Firstname + ' ' +  $_.Lastname 

else

$name = $_.Firstname

$org = $_.EmailAddress.SubString($_.EmailAddress.IndexOf("@") + 1, $_.EmailAddress.IndexOf(".")-$_.EmailAddress.IndexOf("@")-1)

$mailboxexists = [bool](Get-Mailbox $name -Organization $org -ErrorAction SilentlyContinue)

if($mailboxexists)

 $name = $name+"1"


New-Mailbox -Database $org -name $name -UserPrincipalName $_.EmailAddress -Password $Password -FirstName $_.FirstName -LastName $_.LastName -Organization $org 
$l = $_.alias.length
if($l -gt 0)

Get-mailbox $name -organization $org | Set-mailbox -name $name -EmailAddresses @{'+'=$_.alias}

}

Open in new window

string serverName = "eXChange"; //getserver(RecordID);
                    System.Uri serverUri = new Uri(String.Format("http://{0}/powershell?serializationLevel=Full", serverName));
                    string retVal = null;
                    string userName = "tenant\\administrator";
                    string password = "xxxxxx";
                    System.Security.SecureString securePassword = new System.Security.SecureString();

                    foreach (char c in password.ToCharArray())
                    {
                        securePassword.AppendChar(c);
                    }

                    System.Management.Automation.PSCredential creds = new System.Management.Automation.PSCredential(userName, securePassword);

                    RunspaceConfiguration rc = RunspaceConfiguration.Create();
                    WSManConnectionInfo wsManInfo = new WSManConnectionInfo(serverUri, SHELL_URI, creds);
                    // wsManInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;


                    string psScript = string.Empty;



                    using (Runspace rs = RunspaceFactory.CreateRunspace(wsManInfo))
                    {

                       



                        if (File.Exists(scriptpath))
                        {
                            System.IO.StreamReader sr = new System.IO.StreamReader(scriptpath);
                            psScript = sr.ReadToEnd().Replace("$path", csvpath);
                        }
                        else
                            throw new FileNotFoundException("Wrong path for the script file");


                        rs.Open();

                        PowerShell powershell = PowerShell.Create();
                        PSCommand command = new PSCommand();
                        command.AddScript(psScript);
                        powershell.Commands = command;
                        powershell.Runspace = rs;





                        Collection<PSObject> commandResults = powershell.Invoke();
                         System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
                         
                         if (powershell.Streams.Error.Count > 0)
                         {
                             foreach (ErrorRecord err in powershell.Streams.Error)
                             {
                                 stringBuilder.AppendLine(err.ToString() + "DASH");
                             }

                         }
                        // close the runspace
                        rs.Close();
                        // convert the script result into a single string  
                       
                        foreach (PSObject obj in commandResults)
                        {
                            stringBuilder.AppendLine(obj.ToString());
                        }
                        string OutPut =  stringBuilder.ToString();
                        return OutPut;

Open in new window

0
tornadog
Asked:
tornadog
  • 3
  • 3
3 Solutions
 
Em ManCommented:
Hi Torn,

not sure if you visited this microsoft site yet.

http://msdn.microsoft.com/en-us/library/bb332449%28v=exchg.80%29.aspx
0
 
ReneGeCommented:
@tornadog

May I suggest you ask the moderators to add "Scripting Languages" and "Powershell" as zones?

To do this, click on REQUEST ATTENTION and ask for it.

Cheers
0
 
ReneGeCommented:
@taga_ipil:
By the way, you've written a very nice article on PST files in your profile :)
0
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

 
tornadogAuthor Commented:
@taga, yes I have tried that too but my issue is I am connecting to a remote server, so I am using the remoting method.
0
 
tornadogAuthor Commented:
I got it working finally by running my script inside a pssession. This was the blog link that helped me get it running.

http://blogs.msdn.com/b/akashb/archive/2010/03/26/how-to-call-ps1-script-from-managed-code-using-remote-powershell-exchange-2010.aspx
0
 
tornadogAuthor Commented:
found the solution myself
0
 
ReneGeCommented:
Congrads tornadog
The points were un-expected. Thanks :)
0

Featured Post

Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now