【问题标题】:Powershell command works in Powershell but not inside of a script, why?Powershell 命令在 Powershell 中有效,但在脚本中无效,为什么?
【发布时间】:2014-08-13 10:01:53
【问题描述】:

我想将我的 IIS Bidings 输出到 csv 或 txt,我只是在使用该 cmdlet 玩了一下:

Get-ChildItem -path IIS:\Sites

完美运行,使用此命令输出到 .txt 也很完美:

Get-ChildItem -path IIS:\Sites | out-file "D:\_utils\PowerShell Scripts\IISexport\IISExport.txt"

但是,一旦我将它包装到一个函数中,powershell 就会尝试找到物理路径 IIS:\Sites,这当然不存在。

Get-ChildItem : Cannot find drive. A drive with the name 'IIS' does not exist.
At D:\_utils\PowerShell Scripts\IISReport.ps1:8 char:1

到目前为止,我的脚本非常简单:

$today = Get-Date -format M.d.yyyy

function IISexport

{
Get-ChildItem -path IIS:\Sites
}

IISexport | out-file "D:\_utils\PowerShell Scripts\IISexport\IISExport$today.txt"

我错过了什么?我想把它排除在外,因为我想把它放到一个更大的脚本中,从 xx 网络服务器中排除我的网络绑定。

我认为这与控制台中已经给出但不在我的脚本中的环境变量有关。但我不知道如何管理它们。已经试过get-childitem evn: 这给我带来了很多变数。

【问题讨论】:

标签: powershell iis powershell-4.0 web-administration


【解决方案1】:

在脚本顶部添加这一行,它将导入必要的 IIS 模块:

Import-Module WebAdministration;

编辑,感谢@KyleMit:如果您没有安装 WebAdministration,您可能需要先运行(使用提升的权限)

Import-Module ServerManager; Add-WindowsFeature Web-Scripting-Tools

【讨论】:

  • 好有趣,我真的必须为每个会话导入这些模块吗?我以为他们留在机器上。谢谢!工作。
  • 这取决于您如何执行脚本 - 如果脚本执行并退出,那么是的,您需要它。另一方面,如果你在一个保持打开的 PS 窗口中启动脚本,那么你只需要该命令一次(因为在会话期间模块将保持导入状态)。
  • 好的,我以为每台机器只需要导入一次模块。解释一切。
  • 我有类似的问题,但我使用的是 AddType,然后是 WebAdministration 的强名称。为什么 THAT 失败但 Import-Module 工作?
  • 注意,如果你没有安装WebAdministration,你可能需要先运行Import-Module ServerManager; Add-WindowsFeature Web-Scripting-Tools
猜你喜欢
  • 2018-04-01
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多