简体   繁体   English

如何从批处理文件运行 PowerShell 脚本

[英]How to run a PowerShell script from a batch file

I am trying to run this script in PowerShell.我正在尝试在 PowerShell 中运行此脚本。 I have saved the below script as ps.ps1 on my desktop.我已在桌面ps.ps1以下脚本另存为ps.ps1

$query = "SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"
Register-WMIEvent -Query $query -Action { invoke-item "C:\Program Files\abc.exe"}

I have made a batch script to run this PowerShell script我制作了一个批处理脚本来运行这个 PowerShell 脚本

@echo off
Powershell.exe set-executionpolicy remotesigned -File  C:\Users\SE\Desktop\ps.ps1
pause

But I am getting this error:但我收到此错误:

在此处输入图片说明

You need the -ExecutionPolicy parameter:您需要-ExecutionPolicy参数:

Powershell.exe -executionpolicy remotesigned -File  C:\Users\SE\Desktop\ps.ps1

Otherwise PowerShell considers the arguments a line to execute and while Set-ExecutionPolicy is a cmdlet, it has no -File parameter.否则 PowerShell 会将参数视为要执行的一行,而Set-ExecutionPolicy一个 cmdlet,它没有-File参数。

I explain both why you would want to call a PowerShell script from a batch file and how to do it in my blog post here .在我的博客文章中解释了为什么要从批处理文件中调用 PowerShell 脚本以及如何执行此操作

This is basically what you are looking for:这基本上就是你要找的:

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\Users\SE\Desktop\ps.ps1'"

And if you need to run your PowerShell script as an admin, use this:如果您需要以管理员身份运行 PowerShell 脚本,请使用以下命令:

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Users\SE\Desktop\ps.ps1""' -Verb RunAs}"

Rather than hard-coding the entire path to the PowerShell script though, I recommend placing the batch file and PowerShell script file in the same directory, as my blog post describes.不过,我建议将批处理文件和 PowerShell 脚本文件放在同一目录中,而不是硬编码 PowerShell 脚本的整个路径,正如我的博客文章所述。

如果要在没有完全限定路径的情况下从当前目录运行,可以使用:

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& './ps.ps1'"

If you run a batch file calling PowerShell as a administrator, you better run it like this, saving you all the trouble:如果你以管理员身份运行一个调用 PowerShell 的批处理文件,你最好这样运行它,省去你所有的麻烦:

powershell.exe -ExecutionPolicy Bypass -Command "Path\xxx.ps1"

It is better to use Bypass ...最好使用Bypass ...

Small sample test.cmd小样本test.cmd

<# :
  @echo off
    powershell /nologo /noprofile /command ^
         "&{[ScriptBlock]::Create((cat """%~f0""") -join [Char[]]10).Invoke(@(&{$args}%*))}"
  exit /b
#>
Write-Host Hello, $args[0] -fo Green
#You programm...

If you want to run a few scripts, you can use Set-executionpolicy -ExecutionPolicy Unrestricted and then reset with Set-executionpolicy -ExecutionPolicy Default .如果你想运行几个脚本,你可以使用Set-executionpolicy -ExecutionPolicy Unrestricted然后用Set-executionpolicy -ExecutionPolicy Default重置。

Note that execution policy is only checked when you start its execution (or so it seems) and so you can run jobs in the background and reset the execution policy immediately.请注意,仅在您开始执行时(或看起来如此)才会检查执行策略,因此您可以在后台运行作业并立即重置执行策略。

# Check current setting
Get-ExecutionPolicy

# Disable policy
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
# Choose [Y]es

Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 example.com | tee ping__example.com.txt }
Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 google.com  | tee ping__google.com.txt  }

# Can be run immediately
Set-ExecutionPolicy -ExecutionPolicy Default
# [Y]es

Another easy way to execute a ps script from batch is to simply incorporate it between the ECHO and the Redirection characters,(> and >>), example:从批处理中执行 ps 脚本的另一种简单方法是简单地将其合并在 ECHO 和重定向字符之间,(> 和 >>),例如:

@echo off
set WD=%~dp0
ECHO New-Item -Path . -Name "Test.txt" -ItemType "file" -Value "This is a text string." -Force > "%WD%PSHELLFILE.ps1"
ECHO add-content -path "./Test.txt" -value "`r`nThe End" >> "%WD%PSHELLFILE.ps1"
powershell.exe -ExecutionPolicy Bypass -File "%WD%PSHELLFILE.ps1"
del "%WD%PSHELLFILE.ps1"

Last line deletes the created temp file.最后一行删除创建的临时文件。

如果您的 PowerShell 登录脚本在 2012 年服务器上运行 5 分钟(就像我的一样),则服务器上有一个 GPO 设置-“配置登录脚本延迟”默认设置“未配置”这将留下 5 分钟的延迟在运行登录脚本之前。

Posted it also here: How to run powershell command in batch file也在这里发布: 如何在批处理文件中运行 powershell 命令

Following this thread:按照这个线程:
https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/converting-powershell-to-batch https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/converting-powershell-to-batch


you can convert any PowerShell script into a batch file easily using this PowerShell function:您可以使用此 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
    }
}


To convert all PowerShell scripts inside a directory, simply run the following command:要转换目录中的所有PowerShell 脚本,只需运行以下命令:

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

Where is the path to the desired folder.所需文件夹的路径在哪里。 For instance:例如:

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


To convert a single PowerShell script, simply run this:要转换单个PowerShell 脚本,只需运行以下命令:

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

Where is the path to the desired file.所需文件的路径在哪里。

The converted files are located in the source directory.转换后的文件位于源目录中。 ie, <FILE-PATH> or <DIR-PATH> .即, <FILE-PATH><DIR-PATH>

Putting it all together:把它们放在一起:
create a .ps1 file (PowerShell script) with the following code in it:创建一个 .ps1 文件(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
    }
}

# change <DIR> to the path of the folder in which the desired powershell scripts are.
# the converted files will be created in the destination path location (in <DIR>).
Get-ChildItem -Path <DIR> -Filter *.ps1 |
  Convert-PowerShellToBatch


And don't forget, if you wanna convert only one file instead of many, you can replace the following并且不要忘记,如果您只想转换一个文件而不是多个文件,则可以替换以下内容

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

with this:有了这个:

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

as I explained before.正如我之前解释的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM