1

I've written the following script to add a user to MS Live:

$pass = Get-Content D:\PSScripts\pass.txt | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential "user@domain.com", $pass
Connect-MsolService -Credential $cred
New-MsolUser -userprincipalname test@domain.com -Displayname "Johny Tester2"

I can copy and paste the commands to PowerShell line by line and successfully create a new user, but I can't figure out how to run them all from command line.

I saved the above 4 lines in a file at D:\PSScripts\script2.ps1

I created a file: D:\PSScripts\runall.bat with the following content:

powershell.exe "& 'D:\PSScripts\script2.ps1'"

(I also tried without the & sign, without the quotes, without the 'exe', with -command switch)

It looks like it goes through the first two lines and then it throws and error on 'Connect-MsolService' and 'New-MsolUser':

The term 'Connect-MsolService' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I need to be able to execute those commands from another program and running a bat file is my best option. Please help.

Running on Win Server 2008 R2, PowerShell Version 2.0

user1787517
  • 13
  • 1
  • 3

3 Answers3

4

PowerShell 2 doesnt do dynamic module loading, that is however a new feature in PowerShell 3. To fix your issue you can manually import the module into your session using the Import-Module cmdlet. Here's the complete fix.

Import-Module MSOnline
$pass = Get-Content D:\PSScripts\pass.txt | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential "user@domain.com", $pass
Connect-MsolService -Credential $cred
New-MsolUser -userprincipalname test@domain.com -Displayname "Johny Tester2"
  • 1
    This is a better answer than the one that was accepted because it not only explains what should be done, it explains *why*. – alroc Oct 31 '12 at 14:13
1

try adding

import-module MSOnline

at the start of your D:\PSScripts\script2.ps1.

CB.
  • 58,865
  • 9
  • 159
  • 159
0

See full topic here: MSOnline can't be imported on PowerShell (Connect-MsolService error)

What I did to solve the issue was:

Copy the folders called MSOnline and MSOnline Extended from the source

C:\Windows\System32\WindowsPowerShell\v1.0\Modules\MSOnline

to the folder

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules

And then in PS run the Import-Module MSOnline, and it will automatically get the module :D

Community
  • 1
  • 1
Danny Fallas
  • 628
  • 1
  • 5
  • 11