Execute powershell script using psexec - powershell

I am trying to execute PowerShell script on 10 computers on same $env:userprofile path using psexec.But it won't work. If i specify path like "c:\Users\bob\" , it works. Below script is not working.
psexec -u domain\bob -p password -h -d cmd /c powershell.exe -Command "(New-Object System.Net.Webclient).DownloadFile('http://x.x.x.x/1.exe','$env:userprofile\1.exe')"

Related

How to use pipes and filters in psexec?

I want to the fetch the 'Status' of Tomcat service using PsExec and Powershell. As there are few approvals pending with Windows Security team I am forced to use PsExec
I tried executing the following command using PsExec and it works fine
PS C:\> .\PSExec.exe \\10.x.x.x -u DOMAIN\sathish -p mypwd cmd /c "powershell -noninteractive -command Get-Service -Name Tomcat"
Status Name DisplayName
------ ---- -----------
Running Tomcat Apache Tomcat 8.5
However, I would like to fetch the status of Tomcat by filtering the output and it failed with the following message
PS C:\> .\PSExec.exe \\10.x.x.x -u DOMAIN\sathish -p mypwd cmd /c "powershell -noninteractive -command Get-Service -Name Tomcat | Select -ExpandProerty Status"
'Select' is not recognized as an internal or external command, operable program or batch file.
cmd exited on 10.165.135.81 with error code 255.
How to filter the output so that I can get the status of Tomcat ?
I tried the following and it worked
C:\> .\PSExec.exe \\10.x.x.x -u DOMAIN\sathish -p mypwd cmd /c 'powershell -noninteractive -command "Get-Service -Name Tomcat | Select -ExpandProperty Status" '
Open the cmd with single-quotes and execute powershell commands within double-quotes
Thanks all for the help

Downloading a file from a webpage on remote computers using a batch file

When I run this command locally on a remote machine it works:
powershell -Command "(New-Object Net.WebClient).DownloadFile('<WebPath>', 'C:\Users\<user>\Desktop\file.exe')"
When I try the same command remotely using PsExec in a batch file:
(Set downloadFileCommand = powershell -Command "(New-Object Net.WebClient).DownloadFile('%WebPath%', 'C$\Users\<user>\Desktop\file.exe')")
PsExec.exe \\<remote_machine> -u %username% -p %password% -s -d cmd /c %downloadFileCommand%
I am getting "cmd started on remote_machine with process ID #id_number."
However, nothing happened and the download wasn't executed. The suggestions here:
Run PowerShell scripts on remote PC
didn't work for me.
Any suggestions?
Edit:
I managed to download the file through the command line (in cmd) using this command:
PsExec.exe \\<remote_machine> -u <username> -p <password> -d powershell -Command (New-Object Net.WebClient).DownloadFile('<url address','C:\file.exe')
But it doesn't work when I try this in a batch file:
(Set DownloadInstaller = "powershell -Command (New-Object Net.WebClient).DownloadFile('<url address','C:\file.exe')")
PsExec.exe \\<remote_machine> -u %username% -p %password% -h -d cmd /c %DownloadInstaller%
This worked - all in one line. I have a loop variable, a remote computer (%%a). I assumed that when I use PsExec, C:\ ... \file.exe "thinks" of C:\ locally in the remote computer, but that probably wasn't the case.
I had to write it all in one line, since the path in DownloadFile (The location I want to download the file to) is locally in the remote computer (which is a loop variable):
PsExec.exe \\%%a -u %username% -p %password% -h -d cmd /c powershell.exe -Command "&{ (New-Object System.Net.WebClient).DownloadFile('%url%','\\%%a\C$\Users\<username>\Desktop\%file%')}")

Which symbol is escape character in cmd?

I have this code:
powershell -command "& { (New-Object Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file') }"
it's for download file.
When I execute it in cmd on remote server - everything is ok.
But when I want to execute this code from my computer on remote server using paexec, I have some troubles with escape characters.
Command in my CMD:
psexec.exe \\remoteServer.0.1 -u username -p password -dbg -lo D:\PsExec.log cmd /c "powershell -command "& { (New-Object Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file') }""
I try to use ^ symbol, but the same error;
Code using ^ symbol for double-quotes:
psexec.exe \\remoteServer.0.1 -u username -p password -dbg -lo D:\PsExec.log cmd /c "powershell -command ^"& { (New-Object Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file') }^""
Also, I tried to use \ (like in PHP) for escape, but have the same result.
Help with this or give advice how I can remotely download a file using the command line.
Unfortunately CMD uses different escape characters depending on what is escaped and where. There is no single one escape character that would be used everywhere.
In most cases the next character is escaped by prepending it with a caret (^), e.g. in for /f loops:
for /f "tokens=1" %%a in ('type file.txt ^| find "something"') do ...
But sometimes characters are escaped by doubling them, e.g. percent characters (%) in batch scripts:
#echo off
echo %%DATE%%=%DATE%
Sometimes you may even need need to put in other escape characters (like backslashes) because you need to escape something not for CMD, but for the command the string is being passed to:
mountvol | findstr /r \\\\
Your particular scenario shouldn't require additional quotes or escaping, though. Just run the PowerShell commandline directly, without cmd /c:
paexec.exe \\remoteServer.0.1 -u username -p password powershell -command "&{...}"
Is it possible to use powershell the complete way? If so, you could try the following:
New-PsDrive -Name X -Root \\127.0.0.1\c$ -PsProvider FileSystem -Credential (Get-Credential)
Copy-Item -Path X:\RequestedFile.txt -Destination C:\Temp
Remove-PsDrive -Name X
If your destination is a http address you could perform following actions:
Invoke-WebRequest -Uri http://some.uri -Method Get -OutFile C:\temp\myfile -Credential (Get-Credential)
Hope that helps
Instead Of this:
psexec.exe \\remoteServer.0.1 -u username -p password -dbg -lo D:\PsExec.log cmd /c "powershell -command "& { (New-Object Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file') }""
DO this:
psexec.exe \\remoteServer.0.1 -u 'username' -p 'password' powershell.exe -Command "& {(New-Object System.Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file')}"
This should do your work.
Hope it helps.

Error while running a powershell script using Psexec

I am running the below batch file to connect the remote machine & run a powershell script on the remote machine using psexec.
Running batch file on local machine (myscript.bat)
Running Command: myscript.bat \\mymachine
set machinename=%1
#echo " started"
PsExec.exe %machinename% -u myID -p myPwd -i -d cmd /c mkdir C:\test
xcopy DirChk.ps1 %machinename%\C$\test
psexec.exe %machinename% -u myID -p myPwd cmd.exe /c 'echo .|powershell.exe -file C:\Test\DirChk.ps1'
#echo "Completed"
Error:
Starting PsExec service on \\mymachine ...Processing -File
'C:\Test\DirChk.ps1'' failed because the file does not have a '.ps1'
extension. Specify a valid PowerShell script file name, and then try
again.
Try double quotes. Batch files are interpreted by cmd, which doesn't understand single quotes. This should work:
psexec.exe %machinename% -u myID -p myPwd cmd.exe /c "echo .|powershell.exe -file C:\Test\DirChk.ps1"

How to execute sqlcmd from powershell?

I have a string in powershell, which contains a native sqlcmd command. The command itself can be executed successfully in cmd.exe. I have difficulty in executing them in powershell. Anyone can help? Thanks.
This is sql.sql
select ##servername
go
select ##servicename
This is the result when I execute the sqlcmd command from cmd.exe
C:\Users\test>sqlcmd -S "(local)\instance1" -U a -P a -i "c:\temp\sql.sql"
--------------------------------------------------
thesimpsons\INSTANCE1
(1 rows affected)
--------------------------------------------------
INSTANCE1
(1 rows affected)
C:\Users\test>
This is the powershell script to call the sqlcmd command.
$sql = #"
sqlcmd -S "(local)\instance1" -U a -P a -i "c:\temp\sql.sql"
"#
Invoke-Command $sql
When I execute this powershell script, I got the following error.
PS C:\TEMP> $sql = #"
sqlcmd -S "(local)\instance1" -U a -P a -i "c:\temp\sql.sql"
"#
Invoke-Command $sql
Invoke-Command : Parameter set cannot be resolved using the specified named parame
ters.
At line:5 char:15
+ Invoke-Command <<<< $sql
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBin
dingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands
.InvokeCommandCommand
To call a Win32 executable you want to use the call operator & like this:
& sqlcmd -S "(local)\instance1" -U a -P a -i "c:\temp\sql.sql"
You could also stop using the external 'SQLCMD.EXE' and use the Invoke-Sqlcmd cmdlet instead:
Invoke-Sqlcmd is a SQL Server cmdlet that runs scripts that contain statements from the languages (Transact-SQL and XQuery) and commands that are supported by the sqlcmd utility
Just open the 'sqlps' utility and run
Invoke-Sqlcmd -InputFile "C:\temp\sql.sql"
Please see Running SQL Server PowerShell
You can also load the SQL Server snap-ins manually in PowerShell before using 'Invoke-Sqlcmd';
for MS SQL Server 2012 you can do that by running
Import-Module SqlPs
This is how I build some externals command in my scripts
$scriptblock = {fullpath\sqlcmd -S `"(local)\instance1`" <# comment option -S #>`
-U a `
-P a `
-i `"c:\temp\sql.sql`" }
Invoke-Command -ScriptBlock $scriptBlock
You can then use $args variable inside it and even start it remotly.
$scriptblock = {fullpath\sqlcmd -S `"(local)\instance1`" <# comment option -S #>`
-U a `
-P a `
-i `"$($args[0])`" }
Invoke-Command -ScriptBlock $scriptBlock -argumentList "c:\temp\sql.sql" -computer "remote1"
Remark :
This allow to comment each param.
Be careful not to forget a "`" and no space after them where they are at the end of the line.
Use Invoke-Expression rather than Invoke-Command
The first positional parameter of invoke-command is -scriptblock, and it expects a script block argument. To take advantage of a here-string to build the command and then run it with invoke-command, you need to convert the here-string to a script block:
$sql = #"
sqlcmd -S "(local)\instance1" -U a -P a -i "c:\temp\sql.sql"
"#
Invoke-Command ([scriptblock]::create($sql))
Both instance name and username should be fully qualified
<domain_name>\Instanc_name and <domai_name>\Username. Only your instance name is correctly scripted.
This is what worked for me for using sqlcmd from within the powershell script using the & operator, see sample to generate a csv file:
& cmd /c "sqlcmd -S $sv -i $PROCFILE -s, -v varDB = $dbclean -o $filename"
$sv has server name like SERVERNAME\INSTANCE
$PROCFILE is like d:\TSTSQL\Sqlquery.SQL
$filename is d:\TSTSQL\Desiredoutfilename.CSV
$dbclean is a parameter passed to the sql file