Executing an exe with arguments using Powershell - powershell

This is what I want to execute:
c:\Program Files (x86)\SEQUEL ViewPoint\viewpoint.exe /Setvar((POSTSTR $POSTSTR)(POSTEND $POSTEND)) /G:C:\viewpointfile.vpt /D:C:($BEGDATE to $TODDATE).xls
This is what I have tried:
$a = "/Setvar((POSTSTR $POSTSTR)(POSTEND $POSTEND))"
$b = "/G:C:\viewpointfile.vpt"
$c = "/D:C:($BEGDATE to $TODDATE).xls"
$Viewpoint = "c:\Program Files (x86)\SEQUEL ViewPoint\viewpoint.exe"
&$Viewpoint $a $b $c
When I execute this I receive an error stating:
File C:\viewpointfile.vpt "/D:C:($BEGDATE to $TODDATE).xls" not found!
I'm not sure where it gets the extra quotes from. If I run the command with just $a and $b it runs fine.
Any help would be greatly appreciated. Thanks! :)
Update
manojlds suggested echoargs so here it the output from it:
&./echoargs.exe $viewpoint $a $b $c
Arg 0 is C:\Program Files (x86)\SEQUEL ViewPoint\viewpoint.exe
Arg 1 is /Setvar((POSTSTR 20101123)(POSTEND 20111123))
Arg 2 is /G:C:\viewpointfile.vpt
Arg 3 is /D:C:(2010-11-23 to 2011-11-23 PM).xls
It appears that all the arguments are being passed properly. When I run this as a command in cmd.exe it executes perfectly. So something on Powershells end must be messing up the output.
Is there any other way to go about executing this command using Powershell?

I've found the method blogged by Joel Bennett to be the most reliable when calling legacy commands
http://huddledmasses.org/the-problem-with-calling-legacy-or-native-apps-from-powershell/
I've had to use this when calling LogParser from Powershell:
set-alias logparser "C:\Program Files (x86)\Log Parser 2.2\LogParser.exe"
start-process -NoNewWindow -FilePath logparser -ArgumentList #"
"SELECT * INTO diskspaceLP FROM C:\Users\Public\diskspace.csv" -i:CSV -o:SQL -server:"Win7boot\sql1" -database:hsg -driver:"SQL Server" -createTable:ON
"#

Get echoargs.exe from Powershell community extension ( http://pscx.codeplex.com/ ) to figure out the arguments that Powershell sends to your exe.
$a = "/Setvar((POSTSTR $POSTSTR)(POSTEND $POSTEND))"
$b = "/G:C:\viewpointfile.vpt"
$c = "/D:C:($BEGDATE to $TODDATE).xls"
$echoArgs = ".\echoargs.exe"
&$echoArgs $a $b $c
You seem to be passing the arguments fine however, but the viewpoint.exe seems to be acting up. I don't see what you are doing here:
$c = "/D:C:($BEGDATE to $TODDATE).xls"
After C: there is no \ and also your error message that you have pasted shows $BEGDATE and $TODDATE verbatim, which is not possible as they would have been substituted with their values.

If I can't run a command like this it usually works for me with Invoke-Expression. Can't test yours though.
Invoke-Expression "$viewpoint $a $b $c"

Related

Pass arguments from one powershell script to another

I have one powershell script, like this one:
$ErrorActionPreference = "Stop"
$WORKDIR=$args[0]
Write-Host "Num of arguments given: " $args.Count
$AllArguments = ""
for ($i = 1; $i -lt $args.Count; $i += 2) {
$AllArguments = '$AllArguments $args[$i] "$($args[$i+1])"'
}
Write-Host "AllArguments: $($AllArguments)"
Write-Host "Starting .\someotherscript.ps1 in directory $($WORKDIR)"
pushd "$WORKDIR"
& Powershell -File .\someotherscript.ps1 $AllArguments
popd
Basically, this powershell script shoud start another powershell script, but without the first argument. So, e.g. when this script is started with .\firstscript.ps1 C:\some\dir -GiveMeParameter param1, then it should call the other script with the following parameters .\someotherscript.ps1 -GivMeParameter param1.
How to achieve that? At the moment I do not know how to solve this problem.
You can use multiple assignment to extract the first and remaining arguments by doing
$WORKDIR, $RemainingArgs = $args
I'm not sure why you're calling PowerShell again to run the script. You can just run the script directly and use splatting to pass the remaining args to the child script.
.\someotherscript.ps1 #RemainingArgs

remote Multiple invocations using Powershell

I appreciate you taking the time to read this.
My issue is as follows: I'm trying to create a program that uses powershell to do the following:
Take a table generated outside of powershell
Loop calls to a powershell script with the parameters from the table
The powershell script calls a special type of .cmd file and then runs commands on it that are located in a different shared location.
Now my problem is with the 3rd point.
I'm currently using the following to call my script (and the arguements are just hard coded to get it working, they'll be generated by the calls from step 2 later on):
powershell.exe -ExecutionPolicy Bypass -Command {invoke-command -file \\sharedlocation\test5.ps1 -computername server1121 -argumentlist 7058,Jason}
The inside of test5.ps1 is currently:
param(
[Parameter(Mandatory=$true)]
[string] $Var1,
[Parameter(Mandatory=$true)]
[string] $Var2
)
$CommandsPath = "\\sharedlocation\testcommands.cmd"
$path = "C:\"+$Var1+"\TOOLS\"+$Var2+"launchtool.cmd"
$scriptPath = [scriptblock]::Create($path)
$out | invoke-command {PARAM($MyArg) $scriptPath } -ArgumentList $CommandsPath
I've also tried using
$CommandsPath = "\\sharedlocation\testcommands.cmd"
$path = "C:\"+$Var1+"\TOOLS\"+$Var2+"\launchtool.cmd & " + $CommandsPath
$scriptPath = [scriptblock]::Create($path)
$out | invoke-command {$scriptPath }
I've also tried to call with hardcoded testcommands instead of them being in a file.
Now my problem is in both cases, it DOES run launchtool.cmd, but it doesn't pass the testcommands.cmd file.
However when on the machine i run
C:\7058\TOOLS\Jason\launchtool.cmd & \\sharedlocation\testcommands.cmd
It works fine.
Any ideas what I'm doing wrong?
Try, invoke-expression "cmd.exe /c C:\7058\TOOLS\Jason\launchtool.cmd & \sharedlocation\testcommands.cmd"
cmd.exe /c is my best way to ensure consistency between cmd and powershell
Is the UNC Path accessible from powershell? Copy the testcommands.cmd to a local path and try if it works!
$CommandsPath = "\\sharedlocation\testcommands.cmd"
if(Test-Path $CommandsPath)
{
$path = "C:\"+$Var1+"\TOOLS\"+$Var2+"\launchtool.cmd & " + $CommandsPath
$scriptPath = [scriptblock]::Create($path)
$out | invoke-command {$scriptPath }
}

start-process in PowerShell 3.0 script doesn't work but it was working in 2.0

I upgraded our PS version to 3.0 and some of our scripts stopped working. After a lot of debugging I realized there is an issue with the Start-Process command.
Basically, when I run the Start-Process directly in the PowerShell cmd it does run the program with the correct arguments. However, when I run the script, it won't give any error but the program will not run.
The script is a bit long, but this is the way I can test the snippet that's failing.
$SERVER = 'servername'
$PORT = 'xxxx'
$TPath = 'E:\epicor\PowerShell\export\POAutomation\'
$User = 'username'
$Psw = 'password'
$Import = 'PO Combined'
$file = $TPath + 'AutomaticPOHeaders.csv'
$DMTPATH = 'E:\epicor\Epicor905\Client\dmt.exe'
$Param = "-ArgumentList `'-user=`"$User`" -pass=`"$Psw`" -server=$SERVER -port=$PORT -import=`"$Import`" -source=`"$file`" -add=true -update=false -noui=true`'"
Start-Process $DMTPATH $Param -Wait
"Finished"
I even wrote to a log file to check if the $Param string is well formed and if the Start-Process command is also well written. When I copy paste the strings in the log file into the PS command line, they run successfully.
I've been stuck with this more than 4 hours now.
Thanks in advance.
i dont know what dmt is waiting for but this command runs successfully on ps V3.
are you sure about you argumentlist parameter ? and seems to be a mess with your quotes
slight changes : use echoargs.exe instead of DMT and add a switch to not open a new window :
$DMTPATH = 'echoargs.exe'
$Param = "-ArgumentList `'-user=`"$User`" -pass=`"$Psw`" -server=$SERVER -port=$PORT -import=`"$Import`" -source=`"$file`" -add=true -update=false -noui=true`'"
Start-Process -nonewwindow $DMTPATH $Param -Wait
"Finished"
results :
Arg 0 is <-ArgumentList>
Arg 1 is <'-user=username>
Arg 2 is <-pass=password>
Arg 3 is <-server=servername>
Arg 4 is <-port=xxxx>
Arg 5 is <-import=PO Combined>
Arg 6 is <-source=E:\epicor\PowerShell\export\POAutomation\AutomaticPOHeaders.csv>
Arg 7 is <-add=true>
Arg 8 is <-update=false>
Arg 9 is <-noui=true'>
Command line:
"C:\Windows\EchoArgs.exe" -ArgumentList '-user="username" -pass="password" -server=servername -port=xxxx -import="PO Combined" -source="E:\epicor\PowerShell\export\POAutomation\AutomaticPOH
aders.csv" -add=true -update=false -noui=true'
Finished
Can you try to start dmt from cmd.exe ? something like :
$p=#("/C";"dmt.exe";"-user'test'" ....)
Start-Process -NoNewWindow cmd.exe $p
I run into the same problem. I noticed if the -noui=true is removed, it seems to work.

Piping from a variable instead of file in Powershell

Is ther any way in Powershell to pipe in from an virable instead of a file?
There are commands that I need to pipe into another command, right now that is done by first creating a file with the additional commands, and then piping that file into the original command. Code looks somehting like this now:
$val = "*some command*" + "`r`n" + "*some command*" + "`r`n" + "*some command*"
New-Item -name Commands.txt -type "file" -value $val
$command = #'
db2cmd.exe /C '*custom db2 command* < \Commands.txt > \Output.xml'
'#
Invoke-Expression -Command:$command
So instead of creating that file, can I somehow just pipe in $val insatead of Commands.txt?
Try this
$val = #("*some command*1","*some command2*","*some command3*")
$val | % { db2cmd.exe /C $_ > \Output.xml }
You should be able to pipe in from $val provided you use Write-Output or its shorthand echo, but it may also be worth trying passing the commands directly on the command line. Try this (and if it doesn't work I can delete the answer):
PS C:\> filter db2cmd() { $_ | db2cmd.exe ($args -replace '(\\*)"','$1$1\"') }
PS C:\> $val = #"
>> *custom db2 command*
>> *some command*
>> *some command*
>> *some command*
>> "#
>>
PS C:\> db2cmd /C $val > \Output.xml
What happens here is that Windows executables receive their command line from a single string. If you run them from cmd.exe you cannot pass newlines in the argument string, but Powershell doesn't have that restriction so with many programs you can actually pass multiple lines as a single argument. I don't know db2cmd.exe so it might not work here.
The strange bit of string replacement is to handle any double quotes in the arguments: Powershell doesn't quote them and the quoting rules expected by most exe files are a bit bizarre.
The only limitation here would be that $val must not exceed about 32,600 characters and cannot contain nulls. Any other restrictions (such as whether non-ascii unicode characters work) would depend on the application.
Failing that:
echo $val | db2cmd.exe /C '*custom db2 command*' > \Output.xml
may work, or you can use it in combination with the filter I defined at the top:
echo $val | db2cmd /C '*custom db2 command*' > \Output.xml

Executing Powershell script from command line with quoted parameters

I am automating the build of a legacy MS Access application, and in one of the steps, I am trying to make an Access executable (.ADE). I have come up with the following code, which is stored in a file (PSLibrary.ps1):
Add-Type -AssemblyName Microsoft.Office.Interop.Access
function Access-Compile {
param (
[Parameter(Mandatory=$TRUE,Position=1)][string]$source,
[Parameter(Mandatory=$TRUE,Position=2)][string]$destination
)
Write-Output "Starting MS Access"
$access = New-Object -ComObject Access.Application
$access.Visible = $FALSE
$access.AutomationSecurity = 1
if (!(Test-Path $source)) { Throw "Source '$source' not found" }
if ((Test-Path $destination)) {
Write-Output "File '$destination' already exists - deleting..."
Remove-Item $destination
}
Write-Output "Compiling '$source' to '$destination'"
$result = $access.SysCmd(603, $source, $destination)
$result
Write-Output "Exiting MS Access"
$access.quit()
}
If I go into the PowerShell ISE and run the command below, then everything works fine, and the expected output is created:
PS C:>& "C:\Temp\PSLibrary.ps1"
PS C:>Access-Compile "C:\Working\Project.adp" "C:\Working\Project.ade"
However, I can't seem to generate the right hocus-pocus to get this running from the command line, as I would in an automated build. For instance,
powershell.exe -command "& \"C:\\Temp\\PSLibrary.ps1\" Access-Compile \"C:\\Temp\\Project.adp\" \"C:\\Temp\\Project.ade\""
What am I doing wrong?
For complex parameters, you can use Powershell's -EncodedCommand parameter. It will accept a Base64 encoded string. No escaping is needed for quotes, slashes and such.
Consider a test function that will print its parameters. Like so,
function Test-Function {
param (
[Parameter(Mandatory=$TRUE,Position=1)][string]$source,
[Parameter(Mandatory=$TRUE,Position=2)][string]$destination
)
write-host "src: $source"
write-host "dst: $destination"
}
Create command to load the script and some parameters. Like so,
# Load the script and call function with some parameters
. C:\Temp\Calling-Test.ps1; Test-Function "some\special:characters?" "`"c:\my path\with\spaces within.ext`""
After the command syntax is OK, encode it into Base64 form. Like so,
[System.Convert]::ToBase64String([System.Text.Encoding]::UNICODE.GetBytes('. C:\Temp\Calling-Test.ps1; Test-Function "some\special:characters?" "`"c:\my path\with\spaces within.ext`""'))
You'll get a Base64 string. Like so,
LgAgAEMAOgBcAFQAZQBtAHAAXABDAGEAbABsAGkAbgBnAC0AVABlAHMAdAAuAHAAcwAxADsAIAAgAFQAZQBzAHQALQBGAHUAbgBjAHQAaQBvAG4AIAAiAHMAbwBtAGUAXABzAHAAZQBjAGkAYQBsADoAYwBoAGEAcgBhAGMAdABlAHIAcwA/ACIAIAAiAGAAIgBjADoAXABtAHkAIABwAGEAdABoAFwAdwBpAHQAaABcAHMAcABhAGMAZQBzACAAdwBpAHQAaABpAG4ALgBlAHgAdABgACIAIgA=
Finally, start Powershell and pass the encoded string as a parameter. Like so,
# The parameter string here is abreviated for readability purposes.
# Don't do this in production
C:\>powershell -encodedcommand LgAgA...
Output
src: some\special:characters?
dst: "c:\my path\with\spaces within.ext"
Should you later want to reverse the Base64 encoding, pass it into decoding method. Like so,
$str = " LgAgA..."
[Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($str))
# Output
. C:\Temp\Calling-Test.ps1; Test-Function "some\special:characters?" "`"c:\my path\with\spaces within.ext`""
PowerShell like Bash can take single or double quotes
PS C:\Users\Steven> echo "hello"
hello
PS C:\Users\Steven> echo 'hello'
hello
this can alleviate some of the headache, also I think you can use the literal backslashes without escaping.
To run PowerShell, choose
Start Menu Programs Accessories
Windows Powershell Windows Powershell