Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 761
RayofCommand Avatar asked Jun 23 '14 11:06

RayofCommand


People also ask

Why is PowerShell not executing scripts?

This error is caused by the PowerShell Execution Policy. By default, the PowerShell Execution policy is set to Restricted. This means that PowerShell scripts won't run at all. Execution Policies are not designed as a security model, but more to prevent the accidental execution of a PowerShell script.

How do I enable PowerShell scripts in PowerShell?

Press “Windows + I” to open settings and click on “Update & Security”. On the left sidebar, click “For developers”, then scroll down to the “PowerShell” subheading. Tick “change execution policy to allow local PowerShell scripts to run without signing.

How do I run a PowerShell script from a shell script?

To run scripts via the command prompt, you must first start up the PowerShell executable (powershell.exe), with the PowerShell location of C:\Program Files\WindowsPowerShell\powershell.exe and then pass the script path as a parameter to it.


1 Answers

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
like image 162
Raf Avatar answered Sep 19 '22 00:09

Raf