3

So I have a script that works fine when I run it from PowerShell ISE. However, I need to automate it, so I run powershell.exe .\script.ps1, but I get errors about some of the commands not being recognized (they are from a non-standard module).

Any help is appreciated, thanks!

Calvin Li
  • 2,614
  • 3
  • 17
  • 25
  • What are the errors and can you show us the pertinent part of the script you are running. Is your non-standard module sourced in your script? – Matt Jul 19 '14 at 03:38
  • Don't "run the ISE from the command line". Fix your script so that it runs properly regardless of where you run it. – alroc Jul 20 '14 at 15:09

2 Answers2

4

Edit the beginning of your script to import all dependencies(modules). This is good practice as it makes the code more readable and works with both PS 2.0 an 3.0+

script.ps1

#Import example module
Import-Module ActiveDirectory

#Script start
$name = Read-Host "Username"
$user = Get-ADUser $name
.....
Frode F.
  • 52,376
  • 9
  • 98
  • 114
  • This almost did it! Since it was not a standard module, just using the name of the module (e.g., `Import-Module ActiveDirectory`) doesn't work. First I used `Get-Module -ListAvailable` to find the path of the module, then use `Import-Module C:\path\ActiveDirectory` and it worked. – Calvin Li Jul 21 '14 at 18:12
  • :) As longs as the modules have been installed in a module location, `Import-Module ModuleName` should work. You could also do `Get-Module -Listavailable ActiveD* | Import-Module` – Frode F. Jul 21 '14 at 19:07
3

One reason should be that a script is dot sourced or a module is loaded from your profile script. In this case your problem can come from the fact that starting PowerShell from the command line and starting PowerShell ISE does not use systematicaly the same profile script. Have a look at $Profile var in each one and edit the associated file.

$Profile on my ISE :

C:\Users\JPB\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

$Profile on my command Line :

C:\Users\JPB\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

More about profiles.About_Profile

A way to know all your $Profile paths : enter image description here

JPBlanc
  • 70,406
  • 17
  • 130
  • 175