Powershell command works in Powershell but not inside of a script, why?
Asked Answered
C

1

8

I wanted to outfile my IIS Bidings to csv or txt , I am simply playing around a bit using that cmdlet :

Get-ChildItem -path IIS:\Sites

which works perfectly, also outfiling to .txt works perfect using this command :

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

But as soon as I wrap it into a function powershell tries to find the physical path IIS:\Sites which of course does not exist.

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

my script is really simple so far :

$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"

What am I missing ? I would like to outfile this because I would love to put it into a bigger script which outfiles my webbindings from xx webservers.

I think it's related to the env variables which are given already in the console but not inside my script. But I don't know how to manage them. Already tried get-childitem evn: which returned me a lot of variables.

Capparidaceous answered 23/6, 2014 at 11:22 Comment(1)
possible duplicate of Getting "Can't find the drive. The drive called 'IIS' does not exist."Ceilometer
W
19

Add this line at the top of your script, it will import the necessary IIS module:

Import-Module WebAdministration;

EDIT, thanks to @KyleMit: if you don't have WebAdministration installed, you may need to first run (with elevated privilege)

Import-Module ServerManager; Add-WindowsFeature Web-Scripting-Tools
Worrisome answered 23/6, 2014 at 11:28 Comment(6)
okay interesting, do I really have to import these modules for each session ? I thought they remain on machine. Thanks! works.Capparidaceous
That depends how you execute your script - if the script execs and exits then yes, you need it. On the other hand , if you launch the script in a PS window which remains opened then you only need that command once(because the module will remain imported for the duration of the session).Worrisome
Ok I thought I only have to import modules once per machine. Explains everything.Capparidaceous
I have similar problem but I was using AddType and then the strong name of WebAdministration. Why does THAT fail but Import-Module work?Pulmonic
Note, if you don't have WebAdministration installed, you may need to first run (with elevated privilege) Import-Module ServerManager; Add-WindowsFeature Web-Scripting-ToolsCeilometer
Using elevated privileges solved this for me. Thanks!Knesset

© 2022 - 2024 — McMap. All rights reserved.