Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 184 Vote(s) - 3.49 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to run a PowerShell script from a batch file

#1
I am trying to run this script in PowerShell. I have saved the below script as `ps.ps1` on my desktop.

$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

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

But I am getting this error:

![Enter image description here][1]

[1]:

Reply

#2
You need the `-ExecutionPolicy` parameter:

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.
Reply

#3
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][1].

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 -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.


[1]:

[To see links please register here]

Reply

#4
If you run a batch file calling PowerShell as a administrator, you better run it like this, saving you all the trouble:

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

It is better to use `Bypass`...
Reply

#5
If you want to run a few scripts, you can use `Set-executionpolicy -ExecutionPolicy Unrestricted` and then reset with `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

Reply

#6
If you want to run from the current directory without a fully qualified path, you can use:

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

#7
If your PowerShell login script is running after 5 minutes (as mine was) on a 2012 server, there is a GPO setting on a server - 'Configure Login script Delay' the default setting 'not configured' this will leave a 5-minute delay before running the login script.
Reply

#8
Another easy way to execute a ps script from batch is to simply incorporate it between the ECHO and the Redirection characters,(> and >>),
example:

@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.
Reply

#9
Posted it also here:

[To see links please register here]


Following this thread: <br>

[To see links please register here]

<br>
<br>
<br>
**you can convert any PowerShell script into a batch file easily using this PowerShell function:**
```
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
}
}
```

<br>To convert **all** PowerShell scripts inside a directory, simply run the following command:<br>
```
Get-ChildItem -Path <DIR-PATH> -Filter *.ps1 |
Convert-PowerShellToBatch
```
Where <DIR-PATH> is the path to the desired folder. For instance: <br>
```
Get-ChildItem -Path "C:\path\to\powershell\scripts" -Filter *.ps1 |
Convert-PowerShellToBatch
```

<br>To convert a **single** PowerShell script, simply run this:
<br>

```
Get-ChildItem -Path <FILE-PATH> |
Convert-PowerShellToBatch
```
Where <FILE-PATH> is the path to the desired file.
<br>
<br>
The converted files are located in the source directory. i.e., *<FILE-PATH<FILE-PATH>>* or *<DIR-PATH<DIR-PATH>>*.
<br><br>
**Putting it all together:**<br>
create a .ps1 file (PowerShell script) with the following code in it:<br>
```
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
```

<br>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.
Reply

#10
This allows Batch files to contain PowerShell code inside of them (save as `test.cmd` or `test.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 * ...
```
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through