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

r8xiu3jd  于 2023-06-24  发布在  Shell
关注(0)|答案(9)|浏览(239)

我正在尝试在PowerShell中运行此脚本。我已将下面的脚本保存为桌面上的ps.ps1

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

我创建了一个批处理脚本来运行此PowerShell脚本

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

但是我得到了这个错误:

sr4lhrrt

sr4lhrrt1#

你需要-ExecutionPolicy参数:

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

否则,PowerShell会将参数视为要执行的行,而Set-ExecutionPolicy * 是 * 一个cmdlet,它没有-File参数。

hsgswve4

hsgswve42#

我解释了为什么要从批处理文件调用PowerShell脚本以及如何执行in my blog post here
这基本上就是你要找的:

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

如果您需要以管理员身份运行PowerShell脚本,请使用以下命令:

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

我建议将批处理文件和PowerShell脚本文件放在同一个目录中,而不是硬编码到PowerShell脚本的整个路径,正如我的博客文章所描述的那样。

vxqlmq5t

vxqlmq5t3#

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

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

dwthyt8l4#

如果你以管理员身份运行一个调用PowerShell的批处理文件,你最好像这样运行它,这样可以省去所有的麻烦:

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

最好使用Bypass

7lrncoxx

7lrncoxx5#

这允许批处理文件在其中包含PowerShell代码(保存为test.cmdtest.bat

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

Write-Host Hello, $args[0] -fo Green
# * Your program goes here * ...
8iwquhpp

8iwquhpp6#

也在这里发布:如何在批处理文件中运行powershell命令
跟随这个线程:
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

其中是所需文件的路径。
转换后的文件位于源目录中。即

将所有内容放在一起:

创建一个.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

别忘了,如果你只想转换一个文件而不是许多文件,你可以替换以下文件

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

用这个:

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

正如我之前解释过的。

8iwquhpp

8iwquhpp7#

如果你想运行一些脚本,你可以使用Set-executionpolicy -ExecutionPolicy Unrestricted,然后用Set-executionpolicy -ExecutionPolicy Default重置。
请注意,执行策略仅在您开始执行时才会被检查(或者看起来是这样),因此您可以在后台运行作业并立即重置执行策略。

# 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
g6baxovj

g6baxovj8#

另一种从批处理中执行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"

最后一行删除创建的临时文件。

tcomlyy6

tcomlyy69#

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

相关问题