Import-CSV nt recognized

Posted on 2011-10-06
Last Modified: 2012-08-13
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 


$name = $_.Firstname

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

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


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

                    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);
                            throw new FileNotFoundException("Wrong path for the script file");


                        PowerShell powershell = PowerShell.Create();
                        PSCommand command = new PSCommand();
                        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
                        // convert the script result into a single string  
                        foreach (PSObject obj in commandResults)
                        string OutPut =  stringBuilder.ToString();
                        return OutPut;

Open in new window

Question by:tornadog
    LVL 6

    Assisted Solution

    by:Em Man
    Hi Torn,

    not sure if you visited this microsoft site yet.
    LVL 10

    Assisted Solution


    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.

    LVL 10

    Expert Comment

    By the way, you've written a very nice article on PST files in your profile :)

    Author Comment

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

    Accepted Solution

    I got it working finally by running my script inside a pssession. This was the blog link that helped me get it running.

    Author Closing Comment

    found the solution myself
    LVL 10

    Expert Comment

    Congrads tornadog
    The points were un-expected. Thanks :)

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Use email signature images to promote corporate certifications and industry awards.
    "Migrate" an SMTP relay receive connector to a new server using info from an old server.
    In this video we show how to create a Shared Mailbox in Exchange 2013. We show this process by using the Exchange Admin Center. Log into Exchange Admin Center.: First we need to log into the Exchange Admin Center. Navigate to the Recipients >> Sha…
    In this video we show how to create an email address policy in Exchange 2013. We show this process by using the Exchange Admin Center. Log into Exchange Admin Center.:  First we need to log into the Exchange Admin Center. Navigate to the Mail Flow…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now