简体   繁体   中英

Call Powershell function from C#

Hi to all I want to call in C# a powershell script. Inside ps1 file I have implemented a function. Powershell script:

Add-Type -path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'
Add-Type -path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll'


 #$CourseName = Read-host  "Enter site name"
CreateBlogSubsite($SiteName)
Function CreateBlogSubsite($SiteName)
{
$user = "johndoe@tenant.onmicrosoft.com";
$pass = "P3003ksi434!";
$secpw = $pass | ConvertTo-SecureString -AsPlainText -Force
$SiteURL = "https://tenant.sharepoint.com/sites/SalesSite/"
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL);
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($user,$secpw);
$Context.Credentials = $Creds;

Try {

    #Specify Subsite details
    $WebCI = New-Object Microsoft.SharePoint.Client.WebCreationInformation
    $WebCI.Title = $SiteName + " Blog" # sitename
    $WebCI.WebTemplate = "Blog#0" #Blog Site #site template
    $WebCI.Url = $SiteName + "_Blog"
    $SubWeb = $Context.Web.Webs.Add($WebCI)
    $Context.ExecuteQuery()

    $URI = $SiteURL + $WebCI.Url
    return $URI
    #Write-host "Subsite Created Successfully! Url is: " + $SiteName + "1Blog" -ForegroundColor Green
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
} 
}

Here is my console program, where I call PS script:

 static void Main(string[] args)
        {
            // Execute powershell script
            // Initialize PowerShell engine
            var shell = PowerShell.Create();
            //Add the script via a pre-made ps1 file
            shell.Commands.AddScript(@"C:\\Users\\zeb\\source\\CreateCourseBlog.ps1");
            shell.Commands.AddParameter("$SiteName", "Desti");
            // Execute the script
            var results = shell.Invoke(); // I want to get output of Poweshell function
            Console.Write(results);
        }

But it does not works :( . So, does not create subsite when I call script from c#

This should work:

 Runspace rs = RunspaceFactory.CreateRunspace();
 rs.Open();
 using (PowerShell ps = PowerShell.Create())
 {
     ps.Runspace = rs;
     ps.AddScript($@"C:\Users\zeb\source\CreateCourseBlog.ps1 -SiteName Desti");
     ps.AddCommand("Out-String");
     var psOutput = ps.Invoke();

     foreach (var item in psOutput)
     {
         if (item == null) continue;
         Console.WriteLine(item.BaseObject.ToString());
     }

     if (ps.Streams.Error.Count > 0) 
         Console.WriteLine($"Errors ({ps.Streams.Error.Count}):\n");

     foreach (var err in ps.Streams.Error)
         Console.WriteLine(" - " + err);
 }

In addition to this code you should add next code to the top of your powershell script:

Param(
[string] $SiteName
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM