Solved

how to run this powershell script inside  a batch file ?

Posted on 2016-09-18
19
97 Views
Last Modified: 2016-09-22
how to create a .bat file to run this powershell script?to do this automatically:
First i need to open manually powershell.exe and then run this script
I want a .BAT script  to do this automatically with 1 single click


Get-WinEvent -FilterHashTable @{LogName="Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational";StartTime=(get-date).AddDays(-1);ID=1149} | %{						
	New-Object PSObject -Property @{
		MachineName = $_.MachineName
		TimeCreated = $_.TimeCreated
		User = $_.Properties[0].Value            
		Domain = $_.Properties[1].Value            
		SourceIP = $_.Properties[2].Value 
	}
}| Select MachineName,TimeCreated,User,Domain,SourceIP

Open in new window

0
Comment
Question by:john lambert
  • 9
  • 4
  • 4
  • +1
19 Comments
 
LVL 39

Expert Comment

by:footech
ID: 41803656
Easiest way is to save the above PowerShell script to a file, say "script.ps1".
Then in the .BAT file use the following command, customizing the path to your file as appropriate.
powershell.exe -ExecutionPolicy Bypass -File c:\temp\script.ps1

Open in new window

The -executionpolicy parameter may or may not be needed depending on your environment, but it won't hurt anything to have it.
0
 

Author Comment

by:john lambert
ID: 41803659
I did that and cmd window desseapered after 4-5 sec, can u do this?

tell me can u include everything inside 1 single bat?? script.ps1 and also that code???
0
 
LVL 39

Expert Comment

by:footech
ID: 41803678
Yes, it works fine for me.  If you're just running the .BAT by double-clicking, a cmd window normally closes when its work is done.  You can add the -NoExit parameter to the powershell.exe command, or you could add something like a pause command in the .BAT file so that it waits for some action from you before finishing.

No, you can't include all the PowerShell code in a .BAT file because the cmd interpreter doesn't know how to handle it.  It is possible with some simple commands, but certain characters and multiline commands will cause problems.  The closest you can come is to Base64 encode the entire PS script contents (the powershell.exe help, seen by running powershell.exe /?, gives an example).  For the code above that would equate to a .BAT with the following contents.
powershell.exe -encodedcommand RwBlAHQALQBXAGkAbgBFAHYAZQBuAHQAIAAtAEYAaQBsAHQAZQByAEgAYQBzAGgAVABhAGIAbABlACAAQAB7AEwAbwBnAE4AYQBtAGUAPQAiAE0AaQ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HIAYwBlAEkAUAA=

Open in new window

0
 

Author Comment

by:john lambert
ID: 41803812
ok is working but i don't know how to use this base64 code
0
 
LVL 39

Expert Comment

by:footech
ID: 41803981
What do you mean?
I just showed you how to use it.  If you mean you don't know how to generate the Base64 string for a given script, then have you read the help from powershell.exe /? ?
0
 
LVL 7

Expert Comment

by:Senior IT System Engineer
ID: 41804000
John,

YOu may want to try save this script header as .BAT file:

@PowerShell.exe -ExecutionPolicy RemoteSigned -Command "Invoke-Expression -Command ((Get-Content -Path '%~f0' | Select-Object -Skip 2) -join [environment]::NewLine)"
@exit /b %Errorlevel%
# script goes here and below....

Get-WinEvent -FilterHashTable @{LogName="Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational";StartTime=(get-date).AddDays(-1);ID=1149} | %{						
	New-Object PSObject -Property @{
		MachineName = $_.MachineName
		TimeCreated = $_.TimeCreated
		User = $_.Properties[0].Value            
		Domain = $_.Properties[1].Value            
		SourceIP = $_.Properties[2].Value 
	}
}| Select MachineName,TimeCreated,User,Domain,SourceIP

Open in new window


and then insert your script above ..

I've done that already multiple times and it is working great for Scheduled task.
0
 
LVL 68

Expert Comment

by:Qlemo
ID: 41804643
ITSystemEngineer,
it does not make sense to me to run exactly that script as a batch file, when its only purpose is to run a PS script - why not run that PS script directly? That also requires only one file ...

However, that is an approach I had in mind too, but with some more flexibility like the ability to use more than one inline PS script, not having to hard-code how many lines to skip aso.
To show how it works I've added some debugging nonsense.
@echo off

REM ... some CMD commands here ...
echo Batch cmd 1
call :callPS PSScript1
REM ... some CMD commands here ...
echo Batch cmd 2
call :callPS PSScript2
REM ... some CMD commands here ...

exit /b

:callPS label

powerShell.exe -ExecutionPolicy RemoteSigned -Command "$script = Get-Content '%~f0'; Invoke-Expression -Command ($script[(($script | select-string '::%1::').LineNumber)..(($script | select-string '::%1End::').LineNumber-2)] -join [environment]::NewLine)"


exit /b

----------------

::PSScript1::
write-host -foreground red Script1
Get-WinEvent -FilterHashTable @{LogName="Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational";StartTime=(get-date).AddDays(-1);ID=1149} | %{						
	New-Object PSObject -Property @{
		MachineName = $_.MachineName
		TimeCreated = $_.TimeCreated
		User = $_.Properties[0].Value            
		Domain = $_.Properties[1].Value            
		SourceIP = $_.Properties[2].Value 
	}
}| Select MachineName,TimeCreated,User,Domain,SourceIP
::PSScript1End::

----------------

::PSScript2::
write-host -foreground green Script2
::PSScript2End::

Open in new window

1
 
LVL 39

Expert Comment

by:footech
ID: 41805316
Interesting concept.  I'm glad you posted that Qlemo, because it addresses the concerns I had with what ITSystemEngineer posted.
Not sure if it's an approach I would use, but it all depends on need, and of course it's not my question.  :)
0
 
LVL 68

Expert Comment

by:Qlemo
ID: 41805536
I fully agree. Best to have it in your toolkit - and keep it locked there ;-]
1
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:john lambert
ID: 41810403
Qlemo yes ur script working better but command prompt  closes after 4-5 seconds how to make it stay longer
0
 
LVL 68

Expert Comment

by:Qlemo
ID: 41810499
Add a pause before the very first exit /b to wait for a key before leaving the batch file.
1
 

Author Comment

by:john lambert
ID: 41811002
wonderful Qlemoo i love you.....can i paste there the second batch script?

Batch cmd 1
Script1


MachineName : WIN-
TimeCreated : 9/22/2016 6:40:55 PM
User        :
Domain      :
SourceIP    : xxx.15.211.xxx

MachineName : WIN-ERKU994KAAI
TimeCreated : 9/22/2016 12:34:08 PM
User        :
Domain      :
SourceIP    : xxx.15.202.xxx



Batch cmd 2
Script2
Press any key to continue . . .

Open in new window

0
 
LVL 68

Accepted Solution

by:
Qlemo earned 500 total points
ID: 41811220
All write-host and echo but the very first echo are just for showing what to do, and so you see what exactly is executed, so can be removed.
The part
::PSScript2::
write-host -foreground green Script2
::PSScript2End::

Open in new window

determines the second script, which consists of only the write-host. Replace that line with your second PS script.
1
 

Author Comment

by:john lambert
ID: 41811290
thank youuuuuuuuuuuuuuuuuuuuu
0
 

Author Closing Comment

by:john lambert
ID: 41811293
yes Qlemo is the best, a big big thanksssssssss
0
 

Author Comment

by:john lambert
ID: 41811468
ah i remeber something......sometimes u need to type this command first when powershell blocks some event viwer info : First open  poweshell.exe as Administrator then run this command:''Set-ExecutionPolicy remotesigned'' can u include in the scripts or make a new separate one(i think this is better solution)
0
 

Author Comment

by:john lambert
ID: 41811480
is ok this?

@echo off

REM ... some CMD commands here ...
echo Batch cmd 1
call :callPS PSScript1
REM ... some CMD commands here ...
echo Batch cmd 2
call :callPS PSScript2
REM ... some CMD commands here ...
pause
exit /b

:callPS label

powerShell.exe -ExecutionPolicy RemoteSigned -Command "$script = Get-Content '%~f0'; Invoke-Expression -Command ($script[(($script | select-string '::%1::').LineNumber)..(($script | select-string '::%1End::').LineNumber-2)] -join [environment]::NewLine)"


exit /b

----------------

::PSScript1::
write-host -foreground red Script1
Set-ExecutionPolicy remotesigned
::PSScript1End::

----------------

::PSScript2::
write-host -foreground green Script2
::PSScript2End::

Open in new window

0
 
LVL 7

Expert Comment

by:Senior IT System Engineer
ID: 41811686
OK, so the Solution does include some of the code that I posted above but it is just formatted and single line ?

What's wrong with my posted solution ?
1
 

Author Comment

by:john lambert
ID: 41811935
is ok too ur solution
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

This article shows how a content item can be identified directly or through translation of a navigation type. It then shows how this information can be used to create a menu for further navigation.
Create and license users in Office 365 in bulk based on a CSV file. A step-by-step guide with PowerShell script examples.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now