我有一个脚本调用另一个脚本(带参数).被调用的脚本包含Install-WindowsFeaturecmdlet.当我运行脚本时,被调用的脚本会运行,但会返回以下错误:
Install-WindowsFeature : The term 'Install-WindowsFeature' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path
Run Code Online (Sandbox Code Playgroud)
当然,我可以从PowerShell控制台运行cmdlet.我也可以从PowerShell控制台运行被调用的脚本并且Install-WindowsFeature工作正常.那么,从运行cmdlet的脚本调用脚本是否有用呢?这是我的调用代码:
$script = "C:\Path\script.ps1"
$argumentList = @()
$argumentlist += ("-Arg1", "value")
$argumentlist += ("-Arg2", "value")
$argumentlist += ("-Arg3", "value")
Invoke-Expression "$script $argumentList"
Run Code Online (Sandbox Code Playgroud)
在被调用的脚本中,我调用Install-WindowsFeature如下:
if ($someValue) { Invoke-Command -ScriptBlock {Install-WindowsFeature -Name RSAT-AD-Tools} }
Run Code Online (Sandbox Code Playgroud)
我也尝试过如下:
if ($someValue) { Install-WindowsFeature -Name RSAT-AD-Tools }
Run Code Online (Sandbox Code Playgroud)
12/16/16编辑:此脚本在使用Sapien PowerShell Studio构建的GUI中运行.当我将构建类型更改为"Native"时,它可以正常工作.我必须重置我的实验室进行检查,但我怀疑如果我只是在x64上下文中运行它也会运行.此文章解释了为什么我认为这很重要.
在Windows Server 2012 R2上运行
运行环境决定了您可以访问哪些模块。当我在 PowerShell Studio 中创建此项目时,它采用默认的 x86(32 位环境)。这可行,但因为我在 Windows Server 2012 R2(64 位环境)上运行它,所以我无法访问 powershell 模块,例如 Import-Module 和 Install-WindowsFeature。将其更改为 x64 项目解决了我的问题。
为了避免这种情况,请务必确保在操作系统本机的体系结构中运行 PowerShell 脚本和模块。您可以通过正确设置项目(如果使用 PowerShell Studio 等工具)或使用 Martin Brandl 提供的代码验证您是否在该操作系统的本机模式下运行来实现此目的。