Compile Micro Focus Net Express 5.1 Cobol in Powershell - powershell

I am hoping someone might be able to help me with writing a COBOL MF Net Express 5.1 compile command in Powershell. I have the command as it was used in the original batch script. I am currently working on reworking this in Powershell as a build script.
COBOL.EXE "%%inFile%%" OUTDD NOERRQ NOFLAGQ NOQUERY noALTER noanim nobound checkdiv COMP errlist list() FASTLINK omf"gnt" perform-type"osvs" SCHEDULER TARGET"PENTIUM" noTRUNC vsc2(1) listpath"","%%OUTPUT%%";,;,;
My attempt at converting this to Powershell has been like this:
$cobolExe = ".\COBOL.EXE"
$expression = "& $cobolExe `"$($inputfile)`" OUTDD NOERRQ NOFLAGQ NOQUERY noALTER noanim nobound checkdiv COMP errlist list() FASTLINK omf`"gnt`" perform-type`"osvs`" SCHEDULER TARGET`"PENTIUM`" noTRUNC vsc2(1) listpath`"`", `"$binPath\`";,;,;"
Invoke-Expression $expression
Invoke-Expression:
Line |
1 | Invoke-Expression $expression
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| At line:1 char:97 + … GQ NOQUERY noALTER noanim nobound checkdiv COMP errlist list() FASTLI … + ~
An expression was expected after '('. At line:1
| char:221 + … NTIUM" noTRUNC vsc2(1) listpath"", "C:\dev\dimensions\test\bin\";,;,; + ~
Missing expression after unary operator ','. At line:1
| char:223 + … NTIUM" noTRUNC vsc2(1) listpath"", "C:\dev\dimensions\test\bin\";,;,; + ~
Missing expression after unary operator ','.
I successfully have this working with CBLLINK.EXE, but it does not require as many parameters.
$cobolFile = "$Path\cobol.dir"
$cbllinkExe = ".\CBLLINK.EXE"
$expression = "$cbllinkExe -s -o$($outputFile) `"$($inputFile)`" adis adisinit adiskey -u`"$cobolFile`""
Invoke-Expression $expression
Anyone who might have any insight and could provide some assistance, I would very much appreciate it. Please let me know if I can provide anything else?

Calling external exe's/cmd's via PowerShell requires specific attention. It is a well-documented thing.
See these details from Microsoft and others: ---
PowerShell: Running Executables
The Call Operator &
# Example:
& 'C:\Program Files\Windows Media Player\wmplayer.exe' "c:\videos\my home video.avi" /fullscreen
Things can get tricky when an external command has a lot of parameters
or there are spaces in the arguments or paths!
With spaces you have to nest Quotation marks and the result it is not
always clear!
In this case it is better to separate everything like so:
$CMD = 'SuperApp.exe'
$arg1 = 'filename1'
$arg2 = '-someswitch'
$arg3 = 'C:\documents and settings\user\desktop\some other file.txt'
$arg4 = '-yetanotherswitch'
& $CMD $arg1 $arg2 $arg3 $arg4
# or same like that:
$AllArgs = #('filename1', '-someswitch', 'C:\documents and settings\user\desktop\some other file.txt', '-yetanotherswitch')
& 'SuperApp.exe' $AllArgs
cmd /c - Using the old cmd shell
** This method should no longer be used with V3
Why: Bypasses PowerShell and runs the command from a cmd shell. Often
times used with a DIR which runs faster in the cmd shell than in
PowerShell (NOTE: This was an issue with PowerShell v2 and its use of
.Net 2.0, this is not an issue with V3).
Details: Opens a CMD prompt from within powershell and then executes
the command and returns the text of that command. The /c tells CMD
that it should terminate after the command has completed. There is
little to no reason to use this with V3.
# Example:
#runs DIR from a cmd shell, DIR in PowerShell is an alias to GCI. This will return the directory listing as a string but returns much faster than a GCI
cmd /c dir c:\windows
Using Windows PowerShell to run old command line tools (and their
weirdest parameters)
Solution 2A: Use CMD /C
As with the first problem, you can run CMD.EXE itself and pass your
command and its parameters in quotes. Efficiency aside, this will work
fine, since PowerShell will not try to parse the string in quotes.
CMD.EXE /C "ICACLS.EXE C:TEST /GRANT USERS:(F)"
<#
# Results
processed file: C:TEST
Successfully processed 1 files; Failed processing 0 files
#>
..there are more like these.

Related

Calling EXE file inside powershell file

I've tried the following:
Start-Process "C:\Tool\alert.exe" -WindowStyle Hidden
when attempting to run this ps1 file inside powershell ise then I got the following the popup message.
The Publisher could not be verified. Are you sure you want to run this software
my question is : how can I get rid of "The Publisher could not be verified. Are you sure you want to run this software"?
This is due to a setting in Windows that flags .exe files as 'high-risk'. You can unblock them using the Unblock-File command before running the executable.
Get-ChildItem "C:\Tool\alert.exe" | Unblock-File
you can read more about it here: https://winaero.com/blog/how-to-unblock-files-downloaded-from-internet-in-windows-10/
1 - Running external executables is a well-documented use case directly from Microsoft.
2 - You must make sure the exe is not marked as from an untrusted source, meaning, you downloaded this from the internet and it is marked with the internet alternate data stream (ADS). You need to remove this stuff on internet-based downloads, using the cmdlet...
Unblock-File
... or open Windows Explorer, right-click, select properties, unblock. See the help files for details and examples.
'PowerShell running executables'
hit(s)
PowerShell: Running Executables
<#
5. The Call Operator &
Technet Jump
Why: Used to treat a string as a SINGLE command. Useful for dealing with spaces.
In PowerShell V2.0, if you are running 7z.exe (7-Zip.exe) or another command that starts with a number, you have to use the command invocation operator &.
The PowerShell V3.0 parser do it now smarter, in this case you don’t need the & anymore.
Details: Runs a command, script, or script block. The call operator, also known as the "invocation operator," lets you run commands that are stored in variables and represented by strings. Because the call operator does not parse the command, it cannot interpret command parameters
Example:
#>
& 'C:\Program Files\Windows Media Player\wmplayer.exe' "c:\videos\my home video.avi" /fullscreen
Things can get tricky when an external command has a lot of parameters or there are spaces in the arguments or paths!
With spaces you have to nest Quotation marks and the result it is not always clear!
In this case it is better to separate everything like so:
$CMD = 'SuperApp.exe'
$arg1 = 'filename1'
$arg2 = '-someswitch'
$arg3 = 'C:\documents and settings\user\desktop\some other file.txt'
$arg4 = '-yetanotherswitch'
& $CMD $arg1 $arg2 $arg3 $arg4
# or same like that:
$AllArgs = #('filename1', '-someswitch', 'C:\documents and settings\user\desktop\some other file.txt', '-yetanotherswitch')
& 'SuperApp.exe' $AllArgs
<#
7. Start-Process (start/saps)
Technet Jump
Why: Starts a process and returns the .Net process object Jump if -PassThru is provided. It also allows you to control the environment in which the process is started (user profile, output redirection etc). You can also use the Verb parameter (right click on a file, that list of actions) so that you can, for example, play a wav file.
Details: Executes a program returning the process object of the application. Allows you to control the action on a file (verb mentioned above) and control the environment in which the app is run. You also have the ability to wait on the process to end. You can also subscribe to the processes Exited event.
Example:
#>
#starts a process, waits for it to finish and then checks the exit code.
$p = Start-Process ping -ArgumentList "invalidhost" -wait -NoNewWindow -PassThru
$p.HasExited
$p.ExitCode
#to find available Verbs use the following code.
$startExe = new-object System.Diagnostics.ProcessStartInfo -args PowerShell.exe
$startExe.verbs

Trying to run a headless executable command through Powershell that works on cmd line

I am trying to run an executable through powershell to run headless, to install a program onto a VM/LocalHost machine. I can get the wizard to open, but for whatever reason I cannot get it to run headless. Here is the cmd line that I run that works:
start /WAIT setup.exe /clone_wait /S /v" /qn"
This is my attempts in powershell
Start-Process .\setup.exe /S -Wait -PassThru
Start-Process .\setup.exe /S /v /qn -Wait -PassThru
Start-Process setup.exe -ArgumentList '/clone_wait /S /v /qn' -Wait
In the cmd line instance the application installs without issue - in the powershell instance the wizard opens and is on the first "Next" prompt. Any help would be appreciated!
I also attempted to add the additional parameters "/v" and "/qn" which return an error : Start-Process : A positional parameter cannot be found that accepts argument '/v'
The bottom attempt runs but it's not waiting for the installation to complete
You may be overthinking it. Remember that PowerShell is a shell. One of the purposes of a shell is to run commands that you type.
Thus: You don't need Start-Process. Just type the command to run and press Enter.
PS C:\> .\setup.exe /clone_wait /S /v /qn
Now if the executable (or script) you want to run contains spaces in the path or name, then use the call/invocation operator (&) and specify the quotes; for example:
PS C:\> & "\package files\setup.exe" /clone_wait /S /v /qn
(This behavior is the same no matter whether you are at the PowerShell prompt or if you put the command in a script.)
This worked for me. You need to quote the whole argumentlist, plus embed double quotes to pass what you want to /v.
start-process -wait SetupStata16.exe -ArgumentList '/s /v"/qb ADDLOCAL=core,StataMP64"'
Running the command normally and then using wait-process after might be a simpler alternative, if you're sure there's only one process with that name:
notepad
wait-process notepad
To follow-up to all that you have been given thus far. Running executables via PowerShell is a well-documented use case.
PowerShell: Running Executables
Solve Problems with External Command Lines in PowerShell
Top 5 tips for running external commands in Powershell
Using Windows PowerShell to run old command-line tools (and their
weirdest parameters)
So, from the first link provides more validation of what you've been given.
5. The Call Operator &
Why: Used to treat a string as a SINGLE command. Useful for dealing with spaces.
In PowerShell V2.0, if you are running 7z.exe (7-Zip.exe) or another command that starts with a number, you have to use the command invocation operator &.
The PowerShell V3.0 parser do it now smarter, in this case you don’t need the & anymore.
Details: Runs a command, script, or script block. The call operator, also known as the "invocation operator," lets you run commands that are stored in variables and represented by strings. Because the call operator does not parse the command, it cannot interpret command parameters
Example:
& 'C:\Program Files\Windows Media Player\wmplayer.exe' "c:\videos\my home video.avi" /fullscreen
Things can get tricky when an external command has a lot of parameters or there are spaces in the arguments or paths!
With spaces you have to nest Quotation marks and the result it is not always clear!
In this case it is better to separate everything like so:
$CMD = 'SuperApp.exe'
$arg1 = 'filename1'
$arg2 = '-someswitch'
$arg3 = 'C:\documents and settings\user\desktop\some other file.txt'
$arg4 = '-yetanotherswitch'
& $CMD $arg1 $arg2 $arg3 $arg4
# or same like that:
$AllArgs = #('filename1', '-someswitch', 'C:\documents and settings\user\desktop\some other file.txt', '-yetanotherswitch')
& 'SuperApp.exe' $AllArgs
6. cmd /c - Using the old cmd shell
** This method should no longer be used with V3
Why: Bypasses PowerShell and runs the command from a cmd shell. Often times used with a DIR which runs faster in the cmd shell than in PowerShell (NOTE: This was an issue with PowerShell v2 and its use of .Net 2.0, this is not an issue with V3).
Details: Opens a CMD prompt from within powershell and then executes the command and returns the text of that command. The /c tells CMD that it should terminate after the command has completed. There is little to no reason to use this with V3.
Example:
#runs DIR from a cmd shell, DIR in PowerShell is an alias to GCI. This will return the directory listing as a string but returns much faster than a GCI
cmd /c dir c:\windows
7. Start-Process (start/saps)
Why: Starts a process and returns the .Net process object Jump if -PassThru is provided. It also allows you to control the environment in which the process is started (user profile, output redirection etc). You can also use the Verb parameter (right click on a file, that list of actions) so that you can, for example, play a wav file.
Details: Executes a program returning the process object of the application. Allows you to control the action on a file (verb mentioned above) and control the environment in which the app is run. You also have the ability to wait on the process to end. You can also subscribe to the processes Exited event.
Example:
#starts a process, waits for it to finish and then checks the exit code.
$p = Start-Process ping -ArgumentList "invalidhost" -wait -NoNewWindow -PassThru
$p.HasExited
$p.ExitCode
#to find available Verbs use the following code.
$startExe = new-object System.Diagnostics.ProcessStartInfo -args PowerShell.exe
$startExe.verbs

Bypass Task Scheduler is not working. Any Idea or Trick?

I have Powershell 2.0 and Windows 7 in two machines.
Im admin of one but the other has some security restrictions.
Learning in google, i found the next code:
$hour24 = (Get-Date).ToString("HH:00")
& schtasks /create /tn MyBATScheduledTask /sc HOURLY /mo 1 /ST ${hour24} /f /ru SYSTEM /tr "C:\Users\Gabriel\Desktop\MyBat.bat"
That works using Admin rights, but when i try on the second machine gets:
"Access Denied"
I played with other codes also but nothing usefull.
There is a secret? There is possible?
This is no a PowerShell code issue.
Many configs in Windows require you be admin on the box. So, if admin is required by Windows, then admin must be used in the PowerShell session.
Also, that command as written is not really correct. Quoting matters when running external commands / executables.
PowerShell: Running Executables
The Call Operator &
Why: Used to treat a string as a SINGLE command. Useful for dealing
with spaces.
In PowerShell V2.0, if you are running 7z.exe (7-Zip.exe) or another
command that starts with a number, you have to use the command
invocation operator &.
The PowerShell V3.0 parser do it now smarter, in this case you don’t
need the & anymore .
Details: Runs a command, script, or script block. The call operator,
also known as the "invocation operator," lets you run commands that
are stored in variables and represented by strings. Because the call
operator does not parse the command, it cannot interpret command
parameters
Example:
& 'C:\Program Files\Windows Media Player\wmplayer.exe' "c:\videos\my home video.avi" /fullscreen
Things can get tricky when an external command has a lot of parameters
or there are spaces in the arguments or paths!
With spaces you have to nest Quotation marks and the result it is not
always clear!
In this case it is better to separate everything like so:
$CMD = 'SuperApp.exe'
$arg1 = 'filename1'
$arg2 = '-someswitch'
$arg3 = 'C:\documents and settings\user\desktop\some other file.txt'
$arg4 = '-yetanotherswitch'
& $CMD $arg1 $arg2 $arg3 $arg4
# or same like that:
$AllArgs = #('filename1', '-someswitch', 'C:\documents and settings\user\desktop\some other file.txt', '-yetanotherswitch')
& 'SuperApp.exe' $AllArgs

Start-Process powershell with spaces

I have been at this for a long while now, getting to the point where I'm very frustrated. I'm hoping someone can point me in the right direction.
I need to run mysqldump, for 6 specific databases.
I need each spawn to run after the last has finished. It should not run all the commands at the same time. It needs to wait.
I've tried this:
$dump = "C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump.exe"
$args = #('-u','databaseUser','-pMySuperAwesomePasswordHere','--single-transaction','--log-error=c:\backups\mysqldump_error.log',"$database > $backupFilePath\$database.sql")
Start-Process $dump $args -Wait
I've tried this:
$cmd = $backupCmd + $database + " > " + "$backupFilePath\$database.sql"
Write-Host $cmd
invoke-expression $cmd | out-null
How do I execute a command, especially one with redirecting the output to a file on the filesystem?
Thank you.
Redirection is a shell feature. Start-Process will dutifully include the last argument with the database name and the > in the actual argument passed to mysqldump which in turn has no idea what to do with the > at all.
You probably want something like
$args = '-u','databaseUser','-pMySuperAwesomePasswordHere','--single-transaction','--log-error=c:\backups\mysqldump_error.log',"$database"
& "C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump.exe" #args | Out-File $backupFilePath\$database.sql
Since mysqldump is a console application it will wait anyway until it's done before continuing with the script.

PowerShell: Start a process with unquoted arguments

My PowerShell script should start an external executable with specified parameters. I have two strings: The file name, and the arguments. This is what process starting APIs usually want from me. PowerShell however fails at it.
I need to keep the executable and arguments in a separate strings because these are configured elsewhere in my script. This question is just about using these strings to start the process. Also, my script needs to put a common base path in front of the executable.
This is the code:
$execFile = "SomeSetup.exe"
$params = "/norestart /verysilent"
& "$basePath\$execFile" $params | Out-Host
# Pipe to the console to wait for it to finish
This is the actual result (does not work with this program):
Process file name: "C:\My\Base path\SomeSetup.exe"
Process command line: "/norestart /verysilent"
This is what I'd expect to have (this would work):
Process file name: "C:\My\Base path\SomeSetup.exe"
Process command line: /norestart /verysilent
The problem is that the setup recognises the extra quotes and interprets the two arguments as one - and doesn't understand it.
I've seen Start-Process but it seems to require each parameter in a string[] which I don't have. Splitting these arguments seems like a complicated shell task, not something I'd do (reliably).
What could I do now? Should I use something like
& cmd /c "$execFile $params"
But what if $execFile contains spaces which can well happen and usually causes much more headache before you find it.
You can put your parameters in an array:
$params = "/norestart", "/verysilent"
& $basepath\$execFile $params
When you run a legacy command from Powershell it has to convert the powershell variables into a single string that is the legacy command line.
The program name is always enclosed in quotes.
Any parameters that contain a space character are enclosed in double
quotes (this is of course the source of your problem)
Each element of an array forms a separate argument.
So given:
$params = "/norestart /verysilent"
& "$basePath\$execFile" $params
Powershell will run the command:
"\somepath\SomeSetup.exe" "/norestart /verysilent"
The solution is to store separate arguments in an array:
$params = "/norestart","/verysilent"
& "$basePath\$execFile" $params
will run:
"\somepath\SomeSetup.exe" /norestart /verysilent
Or if you already have a single string:
$params = "/norestart /verysilent"
& "$basePath\$execFile" ($params -split ' ')
will work as well.
$execFile = "SomeSetup.exe"
$params = "/norestart /verysilent"
Invoke-Expression ($basePath + "\" + $execFile + " " +$params)
Try it this way:
& $execFile /norestart /verysilent
Bill
Just use single quotes:
$execFile = "SomeSetup.exe"
$params = "/norestart /verysilent"
& "'$basePath\$execFile' $params" | Out-Host
# Pipe to the console to wait for it to finish
Also I would use join-path instead of concatenating the two strings:
$path = Join-Path $basePath $execFile
& "$path $params" | out-host