Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cmdlets not found in command line but available in ISE

I'm trying to create an IIS application and app pool using PowerShell on a Windows Server 2008 R2 VM. The powershell script is as follows:

Param(
    [string] $branchName,
    [string] $sourceFolder
)

if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
    [Security.Principal.WindowsBuiltInRole] "Administrator"))
{ 
    Write-Warning "You do not have Administrator rights to run this script.     `nPlease re-run this script as an Administrator."
    Exit
}

$appPool = $branchName
$site = "Default Web Site"

#Add APPPool
New-WebAppPool -Name $appPool -Force 

#Create Applications
New-WebApplication -Name $branchName -Site $site -PhysicalPath $sourceFolder -   ApplicationPool $appPool -Force    

If I run the script in the PowerShell ISE it works fine but if I run it from a command line (or a batch file using the command line) I get the error

The term New-WebAppPool is not recognized as the name of a cmdlet... etc.

Is there a way that the web administration cmdlets could be installed in the ISE but not the command line?

like image 980
Adamon Avatar asked Jan 18 '16 09:01

Adamon


2 Answers

Assuming that you're using PowerShell v2 (the default version installed with Server 2008 R2) it's as @jisaak suspected: you need to import the module WebAdministration explicitly in your code:

Import-Module WebAdministration

ISE seems to do that automatically.

Another option would be to upgrade to PowerShell v4, which also automatically imports modules when one of their exported cmdlets is used.

like image 185
Ansgar Wiechers Avatar answered Oct 17 '22 20:10

Ansgar Wiechers


For anyone interested, the answer was painfully simple. As suggested, the solution was to import the module, but there was an issue was that it wasn't available after closing the console and reopening it. To solve this I simply had to add the line into the powershell itself so it imports the module at every runtime.

Param(

[string] $branchName,   
[string] $sourceFolder)

if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator"))
{ 
Write-Warning "You do not have Administrator rights to run this script.`nPlease re-run this script as an Administrator."
Exit
}

$appPool = $branchName
$site = "Default Web Site"

*Import-Module WebAdministration*

#Add APPPool
New-WebAppPool -Name $appPool -Force 

 #Create Applications
New-WebApplication -Name $branchName -Site $site -PhysicalPath $sourceFolder -   ApplicationPool $appPool -Force    
like image 1
Adamon Avatar answered Oct 17 '22 22:10

Adamon