在命令行中找不到但在 ISE 中可用的 Cmdlet

Cmdlets not found in command line but available in ISE

我正在尝试在 Windows Server 2008 R2 VM 上使用 PowerShell 创建 IIS 应用程序和应用程序池。 powershell脚本如下:

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    

如果我 运行 PowerShell ISE 中的脚本它工作正常但是如果我 运行 从命令行(或使用命令行的批处理文件)它我得到错误

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

有没有一种方法可以在 ISE 而不是命令行中安装 Web 管理 cmdlet?

假设您使用的是 PowerShell v2(与 Server 2008 R2 一起安装的默认版本),@jisaak 怀疑:您需要在代码中显式导入模块 WebAdministration

Import-Module WebAdministration

ISE 似乎会自动执行此操作。

另一种选择是 upgrade to PowerShell v4,当使用其中一个导出的 cmdlet 时,它也会自动导入模块。

对于任何感兴趣的人来说,答案都非常简单。正如建议的那样,解决方案是导入模块,但存在一个问题,即在关闭控制台并重新打开后它不可用。为了解决这个问题,我只需将该行添加到 powershell 本身,以便它在每次运行时导入模块。

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