배치 파일에서 PowerShell 스크립트를 실행하는 방법
PowerShell power power power power power 。을 래래음음음음음음음음음음음음음음음 the the the the the the the 라고 저장해 두었습니다.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
하지만 다음 오류가 발생합니다.

★★★★★★★★★★★★★★★★가 필요합니다.-ExecutionPolicy★★★★★★★★★★★★★★★★★★:
Powershell.exe -executionpolicy remotesigned -File C:\Users\SE\Desktop\ps.ps1
않으면 하고 PowerShell은 실행할 행으로 간주합니다.Set-ExecutionPolicy cmdlet 입니다.-File파라미터를 지정합니다.
배치 파일에서 PowerShell 스크립트를 호출하는 이유와 방법은 모두 여기 블로그 투고에서 설명합니다.
기본적으로 다음과 같은 것을 찾고 있습니다.
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 스크립트 파일을 블로그 투고에서 설명한 바와 같이 동일한 디렉토리에 배치하는 것이 좋습니다.
완전 수식 경로 없이 현재 디렉토리에서 실행할 경우 다음을 사용할 수 있습니다.
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& './ps.ps1'"
관리자로 PowerShell이라는 배치 파일을 실행하는 경우 다음과 같이 실행함으로써 모든 수고를 덜 수 있습니다.
powershell.exe -ExecutionPolicy Bypass -Command "Path\xxx.ps1"
Bypass
소규모 샘플 테스트.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...
여기에도 투고했습니다.배치 파일에서 powershell 명령을 실행하는 방법
줄에 :
https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/converting-powershell-to-batchhttpscommunity.idera.com/database-tools/powershell/powertips/b/tips/posts/
PowerShell power power power power power power power power power power 。
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
여기서 는 원하는 파일의 경로입니다.
변환된 파일은 소스 디렉토리(<FILE-PATH> 또는<DIR-PATH>)에 있습니다.
「 」 、 「 」
shell1 、 .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
아까 설명 드렸듯이
개의 스크립트를 는, 「」를 사용할 수 .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
배치에서 ps 스크립트를 실행하는 또 하나의 간단한 방법은 ECHO와 리다이렉션 문자(> 및 >) 사이에 ps 스크립트를 삽입하는 것입니다.다음은 예를 제시하겠습니다.
@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"
마지막 행은 생성된 임시 파일을 삭제합니다.
PowerShell 로그인 스크립트가 2012년 서버에서 5분 후에 실행되는 경우 서버에 GPO 설정인 "Configure Login Script Delay(로그인 스크립트 지연 구성)"가 있습니다.기본 설정은 "not configured(설정되지 않음)"입니다.로그인 스크립트를 실행하기 전에 5분간의 지연이 남습니다.
언급URL : https://stackoverflow.com/questions/19335004/how-to-run-a-powershell-script-from-a-batch-file
'programing' 카테고리의 다른 글
| 문자열 형식으로 열거하는 방법 (0) | 2023.04.10 |
|---|---|
| iOS에서 빠른 속도로 응용 프로그램의 화면 잠금을 방지하는 방법 (0) | 2023.04.10 |
| 시작 프로세스에서 표준 출력 및 오류 캡처 (0) | 2023.04.10 |
| 특정 커밋용 Git 패치를 생성하려면 어떻게 해야 합니까? (0) | 2023.04.10 |
| 분기를 변경하지 않고 다른 Git 분기에 있는 파일 보기 (0) | 2023.04.10 |