Powershell脚本未从批处理文件运行

时间:2012-10-31 05:32:57

标签: powershell batch-file

我编写了以下脚本来将用户添加到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"

我可以逐行将命令复制并粘贴到PowerShell并成功创建新用户,但我无法弄清楚如何从命令行运行它们。

我将以上4行保存在D:\ PSScripts \ script2.ps1

的文件中

我创建了一个文件:D:\ PSScripts \ runall.bat,其中包含以下内容:

powershell.exe“&'D:\ PSScripts \ script2.ps1'”

(我也试过没有&符号,没有引号,没有'exe',带-command开关)

看起来它经过了前两行,然后它在'Connect-MsolService'和'New-MsolUser'上抛出并出错:

术语“Connect-MsolService”未被识别为cmdlet,函数,脚本文件或可操作程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。

我需要能够从另一个程序执行这些命令,并且运行bat文件是我的最佳选择。请帮忙。

在Win Server 2008 R2,PowerShell版本2.0上运行

3 个答案:

答案 0 :(得分:4)

PowerShell 2不进行动态模块加载,但这是PowerShell 3中的一项新功能。要解决您的问题,您可以使用Import-Module cmdlet手动将模块导入会话。这是完整的解决方案。

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 :(得分:1)

尝试添加

import-module MSOnline

D:\PSScripts\script2.ps1

的开头

答案 2 :(得分:0)

请在此处查看完整主题:MSOnline can't be imported on PowerShell (Connect-MsolService error)

我为解决这个问题所做的是:

从源

复制名为MSOnline和MSOnline Extended的文件夹
  

C:\ Windows \ System32下\ WindowsPowerShell \ V1.0 \模块\ MSOnline

到文件夹

  

C:\的Windows \ Syswow64资料\ WindowsPowerShell \ V1.0 \模块

然后在PS中运行Import-Module MSOnline,它将自动获取模块:D

相关问题