How to execute a CMD file in remote computer - powershell-2.0

I am looking to execute a command in remote machine using invoke but the .cmd file will call for additional .vbs script. So i guess i may have to mention CScript if so how do i mention both cmd/c and cscript in the below command
Invoke-Command -computername blrscrv01 -ScriptBlock { param($path, $command ) cmd /c $path $command } -args '"C:\windows\system32\cscript.exe"','"/?"'

Your example worked for me when I removed the extra level of quoting.
Invoke-Command -computername blrscrv01 -ScriptBlock { param($path, $command ) cmd /c $path $command } -args 'C:\windows\system32\cscript.exe','/?'
Troubleshooting
Enter a remote session and poke around.
Enter-PSSession -computername blrscrv01
Verify that the target script exists and is accessible.
dir \\lcsap027\deploy\c2.cmd
dir \\lcsap027\deploy
type \\lcsap027\deploy\c2.cmd
Attempt to run the script interactively.
\\lcsap027\deploy\c2.cmd
or
cmd /c \\lcsap027\deploy\c2.cmd
Alternative
Another thing you might try is not invoking a cmd script remotely, but issuing the commands remotely. New-PSSession will return a handle you can use to deal interactively with the remote machine. You can repeatedly issue commands with Invoke-Command and get the results (as primitive data types and generic objects, though, not the actual objects themselves).
Altered Script
Here's an altered version of the script you put in your comment. I've removed the nested Invoke-Command (I don't know why it was necessary, you're already running commands on the remote machine). Since the line breaks got lost in the comment, I don't know if there were any statement separator problems (I'll just assume there weren't, though in its "formatted" form as a one-liner, it would have died horribly because PoSH wouldn't have known where one statement ended and the next began).
param(
[string]$ComputerName,
[string]$User,
[string]$pass
)
Get-PSSEssion | Remove-PSSession
$session = New-PSSession -ComputerName $ComputerName
Invoke-Command -Session $session -ScriptBlock {
param(
[string]$ComputerName,
[string]$Username,
[string]$Password
)
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("x:", "\\machinename\sharename", $false, $Username, $Password)
cmd.exe /c "x:\c2.cmd"
$net.RemoveNetworkDrive("x:")
} -args $ComputerName, $User, $pass
This at least got the remote script to run and produced the expected output. (I emitted the computer name, user name, and file location.)
Bear in mind that this method doesn't employ any transport-/application-layer encryption, so the password is sent cleartext over the network.

Related

Simultaneous PowerShell script execution

I have written the following script for SQL patching:
cls
$computers = Get-Content D:\Abhi\Server.txt
foreach ($line in $computers)
{
psexec \\$line -s -u Adminuser -p AdminPassword msiexec /i D:\SQL_PATCH\rsSharePoint.msi SKIPCA=1 /qb
}
My doubt here is to parallelize this script execution on all the servers mentioned in the text file. Meaning, as soon I start the execution of the script, this should initiate the patching activity on the servers simultaneously and also to track the progess on all the servers, as this script is doing now only for one server.
Kindly help me on this.
Thanks Ansgar Wiechers.
This piece of code did it. It helps in executing the .exe simultaneously on all the servers as well as track their status:
cls
$servers = Get-Content 'D:\Abhi\Server.txt'
$servers | ForEach-Object {$comp = $_
Start-Job -ScriptBlock {psexec \\$input -s -u Adminuser -p AdminPassword C:\SQL_PATCH\SQLServer2008R2SP3-KB2979597-x64-ENU.exe /quiet /action=patch /allinstances /IAcceptSQLServerLicenseTerms} -InputObject $comp}
While (Get-Job -State Running)
{
Get-Job | Receive-Job
#Start-Sleep 2
#Write-Host "Waiting for update removal to finish ..."
}
Remove-Job *

Powershell Parameters

I am extreme newbie to powershell. I have a script that I want to pass a URL as a parameter. The url runs a PHP process that creates and downloads a PDF file then the script prints the pdf and then deletes the pdf. I cannot get the URL parm to work.
Below is my script
$w=$args[0]
Start $w
$Directory = "C:\Users\pslessor\downloads\"
Get-ChildItem -path $Directory -recurse -include *.pdf | ForEach-Object {Start-Process -FilePath $_.fullname -Verb Print -PassThru | %{sleep 5;$_} | kill }
Remove-Item C:\Users\pslessor\downloads\* -include *.PDF
This script is being executed by a batch file PrintPl.bat
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%PrintPl.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%' %1";
And I am testing with testprint.bat
C:\Wget\PrintPl "https://partners.wayfair.com/print_shipping_docs.php?Print=1&printPackingSlips=1&PackingSlipPOs=CS287851107"
The URL is all in one string this editor is forcing the line feed at .php?
The Error I am getting is
The string starting:
At Line:1 Char:25
+ & 'C:\Wget\Printpl.ps1' <<<< 'https://partners.wayfair.com/print_shipping_docs.php?print;
is missing the terminator: '.
At line:1 Char:85
+ & 'C:\Wget\PrintPl.psl' 'https://partners.wayfair.com/print_shipping_docs.php
?print; <<<<
+ CategoryInfo :ParserError: <https://partner...docs.php?print;:
String> [], ParentContainsErrorRecordException
+ FullyqualifiedErrorid : TerminatorExpectedAtEndOfString
'printPackingSlips' is not recognaized as internal or external command,
Operable program or batch file.
'PackingSlipPOs' is not recognized as an internal or external command,
operable program or batch File
This is happening because when you pass the arguments the command interpreter expands your variables and see this:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\Wget\PrintPl.ps1' https://partners.wayfair.com/print_shipping_docs.php? Print=1&printPackingSlips=1&PackingSlipPOs=CS287851107"
So the command that it is trying to execute is C:\Wget\PrintPl.ps1, and it assumes that what comes next are arguments. Since what it is passed has a space, and is not enclosed in quotes or double quotes it assumes that it is multiple arguments. It sees it as:
Execute this script: C:\Wget\PrintPl.ps1
With the following arguments:
$Args[0]=?
$Args[1]=Print=1&printPackingSlips=1&PackingSlipPOs=CS287851107
To stop this from happening you will need to enclose the URL in quotes as well, so your command should look like this:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%' '%1'"
Edit: Ok, that didn't work for your case. So we're going to change this a little bit. Instead of -Command I'm going to suggest you use -File. So your Powershell execution line within the batch file will look like this:
PowerShell -NoProfile -ExecutionPolicy Bypass -File "%PowerShellScriptPath%" %*
You should be able to run the batch file exactly as you previously had been. I'm fairly confident that will work for you.

How Can I Return Exit Code To Variable On Local Computer From Script Run On Remote Computer?

I am attempting to execute a Powershell script on a remote computer from a Powershell window on my local computer using Powershell 2.0. My goal is to store an exit code from the script on the remote computer to a variable on my local computer, whether it be in a local script or just a local Powershell window. Currently all I get back is an error message stating the following . . .
Cannot invoke pipeline because run space is not in the Opened state. Current state of run space is Closed. + CategoryInfo: OperationStopped: Microsoft.Power...tHelperRunspace:ExecutionCmdletHelperRunspace) [], InvalidRunspaceStateException + FullyQualifiedErrorID : RemotePipeLineExecutionFailed
My situation is this . . . I am trying to return an exit code to a variable on my local machine from a script on a remote machine. There are actually two scripts involved here and both are on the remote machine and in the same folder. The first script is called "VerifyBatchExistence.ps1". This file takes as input a batch file called "Batch.ps1", an integer that represents an exit code to be output if "Batch.ps1" does not exist, another integer representing the number of parameters needed by "Batch.ps1", and the variable string(s) needed as input for "Batch.ps1". Within "Batch.ps1" I have the following piece of code which I expect to be triggered when one of my passed-in parameters is invalid. . .
exit 931
Within "VerifyBatchExistence.ps1" I have the following piece of code . . .
Powershell - File .\Batch.ps1 BATCHPARAM1 BATCHPARAM2
$Code1 = $LASTEXITCODE
$Host.SetShouldExit($Code1)
exit
On my local machine, I did the following . . .
$Remote=New-PSSession -ComputerName 7.7.7.7 -Credential $cred
Invoke-Command -Session $Remote -ScriptBlock {$Code1=.\VerifyBatchExistence.ps1 7777 2 .\Batch.ps1 NAME1 NAME2}
$Code2=Invoke-Command -Session $Remote -ScriptBlock {$Code1}
$Code2
After this, I receive the error stated above. Any idea what I am doing wrong or how I can return an exit code to a variable on my local machine from a remote machine which has a script consuming and running a second script? Any answer to this would be appreciated. Thanks.
I do it like this:
invoke-command -session $Remote -scriptblock { mycommand }
$remotelastexitcode = invoke-command -session $Remote -ScriptBlock { $lastexitcode }
if ( $remotelastexitcode -ne 0 )
{
"$remotelastexitcode"
exit 1
}

Remote register of ocx using powershell

I'm trying to register an OCX file on a remote machine using Powershell 2.0.
This doesn't doesn't work:
$LocalOCXPath = "C:\Windows\SysWOW64\dxapi.ocx"
Invoke-Command -ComputerName $ComputerName -ScriptBlock { "C:\windows\system32\Regsvr32.exe $args" } -argumentlist $LocalOCXPath
But this does:
Invoke-Command -ComputerName $ComputerName -ScriptBlock { & 'regsvr32.exe' 'C:\Windows\SysWOW64\dxapi.ocx' }
I really need to be able to pass the path in via a variable, but I don't think I can do that using option 2. And I have no idea why option 1 doesn't work. By doesn't work, I mean that powershell looks like it invokes the command properly, but when I look on the remote machine, the ocx file isn't registered.
I think you are overenginnering, try:
$LocalOCXPath = "C:\Windows\SysWOW64\dxapi.ocx"
Invoke-Command -ComputerName $ComputerName -ScriptBlock { & 'regsvr32.exe' $LocalOCXPath }
Invoke-Command runs the scriptblock in the context of the remote system so your $LocalOCXPath variable doesn't exist there. In PowerShell 3.0 you can force the variable to be seen in the remote context by prefixing it with $Using:, as in $Using:$LocalOCXPath.

Get result from a remote call to msiexec using Powershell

I'm using Powershell on Win 2008r2 to make a remote call to msiexec as follows:
Invoke-Command -session $Session -ScriptBlock{param($arguments) start-process -FilePath "msiexec.exe" -Wait $arguments } -Argument $arguments
Currently I'm checking for success using if(!$?) but this is no good because I've just seen the msiexec process throw a 1638 error (because the app is already installed on the remote server) but the value of $? was True.
Can anyone please tell me how I can capture the 1638 code, or whatever else, is returned by msiexec on the remote server?
Thanks, Rob.
This was a very hackish way to do this, but I got around this by using a global-like variable in terms of $script:functionexitcode which I would assign with the value of the .ErrorCode from the msiexec.exe using Start-Process.
Then in the main part of the PowerShell script, I would test that value if ($functionexitcode -eq 0).
Here is the full snippet from a very similar install scenario with Start-Process:
# Start MSP upgrade to UR
$upgrade = (Start-Process -Filepath $msiexecpath -ArgumentList $argumentlist_BEGIN$argumentlist_MSP$argumentlist_END -PassThru -Wait -ErrorAction Stop)
if ($upgrade.ExitCode -eq 0) {
Write-Host "Upgrade successful. Error code:" $upgrade.ExitCode `
"`nUpgrade logfile location: " $workingdirectory\$msi_logfile_upgrade
$script:FunctionExitCode = $upgrade.ExitCode

Resources