Geeks With Blogs
Developers Friendly
Hi,

Through this post i am trying to demonstrate how to access remote server and create web applications on any given server using PowerShell script from .NET application. Which involves passing values as parameters and executing ps1 script and accessing result set returned from ps1 script.

The same can be achieved using .Net class "ServerManager" class, however which requires lot of settings that need to be done and we might get into lot of permission issues.

Below is the sample code to call ps1 script file, and pass parameters to ps1 file.

 Runspace runspace = RunspaceFactory.CreateRunspace();

                            PowerShell ps = PowerShell.Create();
                            runspace.Open();
                            ps.Runspace = runspace;
                            var useLocalScope = false;
                            ps.AddCommand(@"..\..\WebAdmin.ps1", useLocalScope);
                            ps.AddParameter("site", siteList[j % serverList.Length]);
                            ps.AddParameter("userName", System.Configuration.ConfigurationManager.AppSettings["userName"].Split(';')[j % serverList.Length]);
                            ps.AddParameter("password", System.Configuration.ConfigurationManager.AppSettings["password"].Split(';')[j % serverList.Length]);
                            ps.AddParameter("server", System.Configuration.ConfigurationManager.AppSettings["server"].Split(';')[j % serverList.Length]);
                            ps.AddParameter("website", System.Configuration.ConfigurationManager.AppSettings["siteName"].Split(';')[j % serverList.Length]);
                            ps.AddParameter("applicationName", virtualAppPath.Split('/')[1]);
                            ps.AddParameter("virtualDirectoryName", mobileFolderName);
                            ps.AddParameter("parentApplicationPath", physicalPath);
                            ps.AddParameter("mobilePhysicalPath", physicalPath + "/" + mobileFolderName);
                            ps.AddParameter("templateFolderPath", System.Configuration.ConfigurationManager.AppSettings["baseMobileTemplateFolderPath"].Split(';')[j % serverList.Length] + "*");

                            Collection<PSObject> results = new Collection<PSObject>();
                            results = ps.Invoke();
                            

Below code snippet is ps1 file which will accepts parameters and executes script.

        Param(
        $site = $NULL,
        $userName = $NULL,
        $password = $NULL,
        $server = $NULL,
        $website = $NULL,
        $applicationName = $NULL,
        $virtualDirectoryName = $NULL,
        $parentApplicationPath = $NULL,
        $mobilePhysicalPath = $NULL,
        $templateFolderPath = $NULL
        )
        
        $ScriptRoot = Split-Path $MyInvocation.MyCommand.Path
        $DeployToServerScriptPath = $ScriptRoot + "\MBE_Script.ps1"
        $FTPUser = $userName
        $FTPPassword = $password
        $UserName=$FTPUser
        $Password=$FTPPassword
        $ServerName = $server
        $FTPZipFilePath = 'C:\BE_NextGen'

        $pwd = convertto-securestring $Password -asplaintext -force
        $cred=new-object -typename System.Management.Automation.PSCredential -argumentlist $UserName,$pwd

        invoke-command -computername $ServerName -Credential $cred `
        -filepath $DeployToServerScriptPath  `
        -ArgumentList $website,$applicationName,$virtualDirectoryName,$parentApplicationPath,$mobilePhysicalPath,$templateFolderPath

AS WebAdmin.ps1 internally calls MBE_Script.ps1, below is the script which creates website and assign parent web applications App pool.

Param(
    $website = $NULL,
    $applicationName = $NULL,
    $virtualDirectoryName = $NULL,
    $parentApplicationPath = $NULL,
    $mobilePhysicalPath = $NULL,
    $templateFolderPath = $NULL
)
Set-ExecutionPolicy RemoteSigned
import-module WebAdministration
#New-WebSite -Name mobile -Port 80 -HostHeader TestSite -PhysicalPath "C:\BE_NextGen\Development\Dev2-Feature\BookingEngine\Clients\smart"

#Start Variables Declaration
    $ParentApplicationPath = $parentApplicationPath 
    $MobilePhysicalPath = $mobilePhysicalPath 
    $TemplateFolderPath = $templateFolderPath 
    $WebConfigPath = $ParentApplicationPath + '\Web.config'
    $WebSiteName = $website
    $ApplicationName = $applicationName
    $VirtualDirectoryName = $virtualDirectoryName
    $WebApplication =  "IIS:\Sites\" + $WebSiteName + '\' + $ApplicationName + '\' + $VirtualDirectoryName
#End Variables Declaration

#Start Creates moble folder

    new-item $MobilePhysicalPath -itemtype directory
    
#End Creates moble folder

#Start Copy content to mobile folder from template folder

    Copy-Item -Path $TemplateFolderPath -Destination $MobilePhysicalPath -Force -Recurse
    
#End Copy content to mobile folder from template folder

#Start Copy Web.config

    Copy-Item -Path $WebConfigPath -Destination $MobilePhysicalPath  -Force -Recurse
    
#End Copy Web.config

#Start Creates new virtual directory under given application under a given site

    Try{
            Set-ExecutionPolicy RemoteSigned
            import-module WebAdministration
            New-WebVirtualDirectory -Site $WebSiteName -Application $ApplicationName -Name $VirtualDirectoryName -PhysicalPath $MobilePhysicalPath
        } Catch [System.IO.FileNotFoundException]{
            New-WebVirtualDirectory -Site $WebSiteName -Application $ApplicationName -Name $VirtualDirectoryName -PhysicalPath $MobilePhysicalPath
            Break
        } 
    
#End Creates new virtual directory under given application under a given site

#Start convert Virtual Directory to Application

    ConvertTo-WebApplication $WebApplication
    
#End convert Virtual Directory to Application

#Start Assign Parent Application Pool

    $appPool = (Get-Item "IIS:\Sites\$WebSiteName\$ApplicationName" | Select-Object applicationPool).applicationPool
    Set-ItemProperty "IIS:\Sites\$WebSiteName\$ApplicationName\$virtualDirectoryName" ApplicationPool $appPool
    
#End Assign Parent Application Pool


Hope this helps anyone!

Thanks!
Posted on Friday, January 3, 2014 1:53 AM .NET , IIS , PowerShell | Back to top


Comments on this post: Creating website in remote server using PowerShell from .NET application

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Manjunath K | Powered by: GeeksWithBlogs.net