【问题标题】:Powershell script not running from batch filePowershell脚本未从批处理文件运行
【发布时间】:2012-10-20 13:10:03
【问题描述】:

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

【问题讨论】:

    标签: powershell batch-file


    【解决方案1】:

    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"
    

    【讨论】:

    • 这是一个比被接受的答案更好的答案,因为它不仅解释了应该做什么,还解释了为什么
    【解决方案2】:

    尝试添加

    import-module MSOnline
    

    D:\PSScripts\script2.ps1 的开头。

    【讨论】:

      【解决方案3】:

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

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

      从源中复制名为 MSOnline 和 MSOnline Extended 的文件夹

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

      到文件夹

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

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

      【讨论】:

        猜你喜欢
        • 2013-10-20
        • 2013-02-18
        • 2015-01-03
        • 2020-03-22
        • 1970-01-01
        • 1970-01-01
        • 2011-06-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多