【问题标题】:How to run powershell command in batch file如何在批处理文件中运行powershell命令
【发布时间】:2018-02-14 15:29:43
【问题描述】:
@ECHO off

$BIOS= Get-WmiObject -computername "BAHRIATSG2-PC" -Namespace 
root/hp/instrumentedBIOS -Class HP_BIOSSettingInterface

$BIOS.SetBIOSSetting('Setup Password','<utf-16/>TheBIOSPassword','<utf-16/>')

pause

当我保存为 .bat 文件并运行时它不起作用,否则当我手动输入时它在 powershell 中正常工作..

【问题讨论】:

标签: powershell batch-file


【解决方案1】:

将您的 PowerShell 代码放入其中,

powershell -Command "& {}"

记得用; 分隔所有语句,并用带引号的字符串将" 括起来,即使用""

powershell -Command "& {$BIOS= Get-WmiObject -computername ""BAHRIATSG2-PC\"" -Namespace root/hp/instrumentedBIOS -Class HP_BIOSSettingInterface; $BIOS.SetBIOSSetting('Setup Password','<utf-16/>TheBIOSPassword','<utf-16/>')}"

【讨论】:

  • 如果其他人像我一样遇到这个问题——执行这样的命令时使用foreach-object 而不是% 别名可能会有所帮助。否则,可能会导致Expressions are only allowed as the first element of a pipeline 错误。
【解决方案2】:

我认为this is是最简单最清晰的方式,因为它不需要任何多余的开关;只是简单的 PowerShell 代码:

@ECHO off

PowerShell ^
   $BIOS= Get-WmiObject -computername \"BAHRIATSG2-PC\" -Namespace;  ^ 
   root/hp/instrumentedBIOS -Class HP_BIOSSettingInterface;  ^
   $BIOS.SetBIOSSetting('Setup Password','<utf-16/>TheBIOSPassword','<utf-16/>')

pause

只需在每行末尾添加一个; ^ 并用反斜杠转义每个引号。

【讨论】:

    【解决方案3】:

    关注这个话题:
    https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/converting-powershell-to-batch


    您可以使用此 PowerShell 函数轻松地将任何 PowerShell 脚本转换为批处理文件:

    function Convert-PowerShellToBatch
    {
        param
        (
            [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
            [string]
            [Alias("FullName")]
            $Path
        )
     
        process
        {
            $encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes((Get-Content -Path $Path -Raw -Encoding UTF8)))
            $newPath = [Io.Path]::ChangeExtension($Path, ".bat")
            "@echo off`npowershell.exe -NoExit -encodedCommand $encoded" | Set-Content -Path $newPath -Encoding Ascii
        }
    }
    


    要转换目录中的所有 PowerShell 脚本,只需运行以下命令:

    Get-ChildItem -Path <DIR-PATH> -Filter *.ps1 |
      Convert-PowerShellToBatch
    

    所需文件夹的路径在哪里。例如:

    Get-ChildItem -Path "C:\path\to\powershell\scripts" -Filter *.ps1 |
      Convert-PowerShellToBatch
    


    要转换 单个 PowerShell 脚本,只需运行以下命令:

    Get-ChildItem -Path <FILE-PATH> |
      Convert-PowerShellToBatch
    

    所需文件的路径在哪里。

    转换后的文件位于源目录中。即,

    【讨论】:

      【解决方案4】:

      powershell有自己的脚本文件类型,扩展名为.ps1

      将您的代码保存到 .ps1 文件,然后从批处理文件运行它:

      powershell xxx.ps1

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-27
        • 2019-11-15
        • 1970-01-01
        • 2020-09-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多