Powershell PSEXEC not working via Control-M - powershell

PS Version: 2.0
Hi All,
I am trying to run the batch file from a powershell script using psexec.
The script runs fine while triggering manually or using windows task scheduler; however, powershell get triggered from Control-m but do not complete the part where psexec is used. The rest part of powershell script runs fine.
Below is the function which is not working, besides it do not give any error, it just freezes the script:
function Archive_Logs($Server_Name,$Tool_Path,$Name)
{
foreach($TPath in $Tool_Path){
C:\Windows\System32\PsExec.exe \\$Server_Name "$TPath\ziplogs.bat"
if($LastExitCode -eq 0)
{
"$Name Server logs archive Started successfully at $(Get-Date)" | Out-File $LOGFILE -Append
}
}
}
The account used by Control-M is local admin on the servers.

How are you calling the Powershell? When you create a .bat file and invoke it from there it fixes a lot of issues, e.g, bat file contains 1 line -
powershell -command "& C:\MyPSscripts\archiver.ps1"
See -
https://communities.bmc.com/thread/117415

Related

Trying to run an exe remotely on another server using Powershell and failing

We have Alteryx on several servers and want to be able to run jobs remotely from either command line or powershell, not through Alteryx API.
I have run alteryx flows locally from command line and powershell locally for years but now with multiple servers we have need to execute certain flows this way but to trigger from a react web app. We tried the API and it works but jobs often queue for too long and we need near realtime response and these jobs run in seconds. Our solution is to trigger outside the Alteryx API for immediate execution on a worker node with excess resources.
Our problem is that when testing the script which works well if run locally it runs all other commands fine except the execution of the alteryxenginecmd.exe program.
if I use Start-Process with passthru it generates a process but no output from the alteryx job and no errors detected.
If I use Call operator & if fails saying it can;t find the workflow, so the alteryxenginecmd.exe is firing but not reading or receiving the full path of the flow to run as the parameter. but it works fine locally.
I have used creds to force a sign on to clear any credential issue with no change in result.
I know Powershell has some oddities and maybe there is some tweak to how a command must be specified if the script is run from a remote server?
This is the script I want to run from remote server which does work fine in any of the 4 scenarios shown
$rundate = (Get-Date -format 'u') -replace "-","" -replace ":","" -replace " ","-"
$Pgm2Run = "\<somepath>\RunScriptRemote\RunRemoteTest2 - NoDB.yxmd"
$Bat2Run = "\\<somepath>\RunScriptRemote\RunRemoteTestJob.bat"
$JobLogFile = "\<somepath>\RunScriptRemote\LogsJob\JobTranscript $rundate.txt"
$ScriptLogFile = "\<somepath>\RunScriptRemote\LogsScript\RunJobTranscript $rundate.txt"
Start-Transcript -Path $ScriptLogFile
echo " "
echo "$rundate Start --> "
Echo "$rundate Before Start-Process"
#1 Start-Process -filepath "AlteryxEngineCmd.exe" -ArgumentList `"$Pgm2Run`" -RedirectStandardOutput $JobLogFile -Wait -PassThru
#2 Start-Process -filepath $Bat2Run -RedirectStandardOutput $JobLogFile -Wait -PassThru
#3 & AlteryxEngineCmd.exe "$Pgm2Run"
AlteryxEngineCmd.exe "$Pgm2Run"
echo "$rundate After Start-Process"
echo "$rundate End --> "
Stop-Transcript
This command run on Server1 to execute the script above on server2
Invoke-Command -ComputerName server2 -FilePath "\\<somepath>\RunScriptRemote\RunAlteryxAndLogIt.ps1"
And this is the result:
20200831-094309Z Before Start-Process
AlteryxEngineCmd.exe Version 2019.4.8.22007 © Alteryx, Inc. - All Rights Reserved.
Started running \\<somepath>\RunRemoteTest2 - NoDB.yxmd
Error - Alteryx Engine: Can't read the file "
Invoke-Command -ComputerName server2 -FilePath "\\<somepath>\RunScriptRemote\RunRemoteTest2 - NoDB.yxmd"
Finished in 0.020 seconds with 1 error
20200831-094309Z After Start-Process
I am not sure it is a powershell thing, it may well be an Alteryx thing because the issue seems to be executing that one exe properly. the script triggers properly from remote server and I tested other commands and all worked, I just can't seem to get the one executing this exe to work when run remotely though it works fine locally when same script is run locally. its like a barrier betweek a script running another script.
Any powershell experts familiar with running exe's remotely from another server?

Jenkins to call powershell script but doesn't execute

Is there a way wherein Jenkins call a powershell script and just stops without waiting for an output? I don't want it to run under the context of jenkins. Jenkins would be used ONLY to pass the form parameters.
Reason : Jenkins doesn't work quite well with Internet explorer COM objects because script works fine when called directly or task scheduler but fails using Jenkins at few steps. Tried multiple work-around but failed.
So, the resolution is that I would call the script using Jenkins only so that it runs under the context of powershell only. Jenkins would be used ONLY to pass the form parameters.
Regards,
Rahul
powershell Start-Job command should work
powershell script: '''
Start-Job {
param($someArgument)
// set location as current directory
Set-Location $using:PWD
//start a command
PowerShell -NoProfile -ExecutionPolicy Bypass -Command .\myscript.ps1
} -Name "myJob1" -ArgumentList $someArgument
'''

Can't load Powershell module when executing from installer

I'm having a simple PowerShell script which import a certificate:
$certificate_file_name = "C:\Files\Plugins\certi1.cer"
$root_cert_folder_path = 'Cert:\LocalMachine\Root'
try
{
$certificate_obj = Import-Certificate -FilePath $certificate_file_name -CertStoreLocation $root_cert_folder_path
}
catch
{
$ErrorMessage = $_.Exception.Message
write-output $ErrorMessage
}
When running the script manually - it's working fine.
In addition, I have an installshield project that have 1 action item - executing the above script.
After building the installer and running it I get the error `The 'Import-Certificate' command was found in the module 'PKI', but the module could not be loaded. For more information, run 'Import-Module PKI'.
Why does it happens? How can it be solved?
`
I found a workaround:
Instead of adding my certificate with Powershell, I did it with batch, that made it work both when running manually and when called as part of installation process.
The batch script is super simple:
Certutil -addstore -f "TrustedPublisher" "path\to\cert\file.cer"
Certutil -addstore -f "Root" "path\to\cert\file.cer"
Since Installshield only supports running powershell scripts , I wrapped the batch with powershell that calls it:
cmd.exe /c 'path\to\batch\script\addCertToRootAndPublisher.bat'

Windows Task Scheduler Powershell get URL and download file

I am struggling with automating download of a file from website that opens a new tab when download is triggered and closes it right before the prompt to Save/Open/Close comes up in the main window. The script itself works just fine when launched manually until I try it in Task Scheduler. It runs great until it snags on the download. I've included a code to capture the URL of the file that needs to be downloaded and then pass it to Invoke-WebRequest which works fine out of PowerShell ISE but doesn't return any results when launched from Task Scheduler. I've included the counter and test file creation into the code to see if contents of do-while execute at all, and all 10 attempts were recorded. It's the part that searches through active URLs that's not returning results when launched via Task Scheduler.
# >> Keep trying to capture the CSV download link
$i = 1
Do {
$i | Add-Content -Path "C:\userfolder\try.txt"
$urls = (New-Object -ComObject Shell.Application).Windows() |
Where-Object {$_.LocationUrl -like "https://sitename.com/ReportViewer*"} |
Where-Object {$_.LocationUrl}
$reportURL = #($urls)[0].LocationURL
$i ++
}
While ($reportURL -eq $NULL -and $i -le 10)
# >> Send download link to web request and save to file
Invoke-WebRequest -Uri $reportURL -OutFile "C:\userfolder\ProfileList.csv"
I have tried the Wscript.Shell AppActivate and SendKeys('%S') before but the AppActivate wouldn't work probably because the PowerShell console window was hijakcing focus when launched via Task Scheduler. The task is set to execute powershell.exe with Arguments: C:\userfolder\CPdownload.ps1 -RunType $true, - and Start in: C:\userfolder. Run: only when user is logged in and with highest privileges; configured for Windows Server 2012 R2.
I've also tried launching the shell script through batch file from Task Scheduler with exactly the same result.
Thanks in advance for any pointers.
Probably your task needs to be run in interactive mode. By default scheduled tasks are run in Session 0. You can schedule task for interactive mode with /IT parameter. Check the following link for more info
https://msdn.microsoft.com/en-us/library/bb736357(VS.85).aspx
Old post however besides changing the script to interactive mode (this fixes it) you can change the Powershell execution policy to unrestricted (Set-ExecutionPolicy -ExecutionPolicy Unrestricted) if you wish to run the script outside of interactive mode. Just thought I'd post as recently come across this myself.

PowerShell: Starting the CLR Failed with HRESULT 8007000e

I'm getting the following error when running PowerShell scripts on a remote server:
Starting the CLR Failed with HRESULT 8007000e
This is basically how I'm running/calling the scripts:
On the local server I'm running a CMD script that calls a PowerShell script to create a remote session to a remote server. In the PowerShell script I also call a CMD script to run on the remote server like so:
$Script = [scriptblock]::create("cd $BuildPath | cmd.exe /c install.cmd $apptype")
The install.cmd script runs on the remote server and calls a PowerShell script that executes a series of tasks.
powershell ./Install.ps1 -BuildNum %BUILDNUM%
After the tasks are complete, the PowerShell script then calls another PowerShell script to run a separate series of tasks. This is when I hit the above error, when the second PowerShell script is called.
This is how the second PS1 script is called from the first PowerShell script:
powershell "& {. $BinToolsSrc\PostInstallValidation.ps1 -BuildNum $BuildNum -Test 'True'; Run-Validation -App $App -AppLoc $AppLoc -Env $Env:ENV -Site $Site -AppPool $AppPool -Config $Config -EnvConfig $EnvConfig -DllPath $DllPath}"
What usually causes the type of CLR error that I'm getting and how do I resolve it?
NOTE: I do not get this error when I run the install script locally on the remote server.
Thanks in advance!
UPDATE: Installing PowerShell 3 on the remote server seems to have solved the problem as it targets the .NET 4.0 runtime.
I too had the same problem because I have changed some path settings in my VScode unknowingly.
I have changed the settings to command prompt which works fine for me now...(This might not be the best solution though).screenshot