Powershell命令在Powershell中工作但不在脚本内部,为什么?

Ray*_*and 6 iis powershell web-administration powershell-4.0

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

Get-ChildItem -path IIS:\Sites
Run Code Online (Sandbox Code Playgroud)

哪个工作完美,也可以使用此命令完成outtiling到.txt:

Get-ChildItem -path IIS:\Sites | out-file "D:\_utils\PowerShell Scripts\IISexport\IISExport.txt"
Run Code Online (Sandbox Code Playgroud)

但是一旦我将它包装到函数中,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
Run Code Online (Sandbox Code Playgroud)

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

$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"
Run Code Online (Sandbox Code Playgroud)

我错过了什么?我想将其归档,因为我希望将它放入一个更大的脚本中,该脚本从xx webservers中删除了我的webbindings.

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

Raf*_*Raf 16

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

Import-Module WebAdministration;
Run Code Online (Sandbox Code Playgroud)

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

Import-Module ServerManager; Add-WindowsFeature Web-Scripting-Tools
Run Code Online (Sandbox Code Playgroud)

  • **注意**,如果您没有安装`WebAdministration`,您可能需要首先运行(具有提升的权限)`Import-Module ServerManager; 添加 WindowsFeature Web 脚本工具` (2认同)