NUnit access denied error in dotcover.exe - powershell

I am writing PowerShell script for dotCover to generate coverage report using NUnit-console.exe
After I run the script -
$testRunner="C:\Program Files (x86)\NUnit 2.6.2\bin\nunit-console.exe"
$testContainers="path/to/test1.dll","path/to/test2.dll"
$dotcover="D:\JetBrains.dotCover.CommandLineTools.2019.3.4\dotcover.exe"
foreach($test in $testContainers)
{
$testAssembly=Get-Item $test
$testName= $testAssembly.BaseName
&$dotcover cover /TargetExecutable=$testRunner /TargetArguments=$test /Output="D:\JetBrains.dotCover.CommandLineTools.2019.3.4\TestReport\$testName.dcvr"
}
$testReports=$testContainer|%{
$testAssembly=Get-Item $test
$name= $testAssembly.BaseName
return ("D:\JetBrains.dotCover.CommandLineTools.2019.3.4\TestReport\{0}.dcvr" -f $name)
}
$testReportArguments=[String]::Join(";",$testReports)
&$dotcover merge /Source="$testReportArguments" /Output="D:\JetBrains.dotCover.CommandLineTools.2019.3.4\TestReport\mergedReport.dcvr" /ReportType="DCVR"
&$dotcover report /Source="D:\JetBrains.dotCover.CommandLineTools.2019.3.4\TestReport\mergedReport.dcvr" /Output="D:\JetBrains.dotCover.CommandLineTools.2019.3.4\TestReport\mergedReport.html" /ReportType="HTML"
It is giving the following error-
Unhandled Exception:
System.UnauthorizedAccessException: Access to the path 'C:\Program Files (x86)\NUnit 2.6.2\bin\TestResult.xml' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String
msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
at System.IO.StreamWriter..ctor(String path)
at NUnit.ConsoleRunner.ConsoleUi.Execute(ConsoleOptions options)
at NUnit.ConsoleRunner.Runner.Main(String[] args)
Even though that TestResult.xml file is not at that location it is at-
C:\Program Files (x86)\NUnit 2.6.2\doc\files\TestResult.xml
but I copied that file and put it to the bin folder but still the error persists.
Is this problem related to rights or something? any way to get rid of this?
and after this the execution is at halt neither failing nor passing.

Anytime you see 'Access Denied', then yes, it's a permissions / ACL problem. So, you do need to check that.
Honestly, I'd suggest adding those 'exe' paths to your Windows System Path or the PowerShell environment path. However, taking what you've shown thus far, as per the link I included in my comment:
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
So, this change should get you going. Again, I don't use the tool, so no way to validate and thus you may need to tweak.
See also:
Implementing DotCover from Powershell
$testRunner = 'C:\Program Files (x86)\NUnit 2.6.2\bin\nunit-console.exe'
$testContainers = 'path/to/test1.dll','path/to/test2.dll'
$dotcover = 'D:\JetBrains.dotCover.CommandLineTools.2019.3.4\dotcover.exe'
foreach($test in $testContainers)
{
$testAssembly = Get-Item $test
$testName = $testAssembly.BaseName
$arg1 = 'cover'
$arg2 = '/TargetExecutable = $testRunner'
$arg3 = '/TargetArguments = $test'
$arg4 = '/TargetExecutable = $testRunner'
$arg5 = '/Output = "D:\JetBrains.dotCover.CommandLineTools.2019.3.4\TestReport\$testName.dcvr"'
& $dotcover $arg1 $arg2 $arg3 $arg4 $arg5
}
$testReports = $testContainer |
%{
$testAssembly = Get-Item $test
$name = $testAssembly.BaseName
return ('D:\JetBrains.dotCover.CommandLineTools.2019.3.4\TestReport\{0}.dcvr' -f $name)
}
$testReportArguments = [String]::Join(';',$testReports)
$arg1 = 'merge'
$arg2 = '/Source = $testReportArguments'
$arg3 = '/Output = "D:\JetBrains.dotCover.CommandLineTools.2019.3.4\TestReport\mergedReport.dcvr"'
$arg4 = '/ReportType = "DCVR"'
& $dotcover $arg1 $arg2 $arg3 $arg4
$arg1 = 'report'
$arg2 = '/Source = "D:\JetBrains.dotCover.CommandLineTools.2019.3.4\TestReport\mergedReport.dcvr"'
$arg3 = '/Output = "D:\JetBrains.dotCover.CommandLineTools.2019.3.4\TestReport\mergedReport.html"'
$arg4 = '/ReportType="HTML"'
& $dotcover $arg1 $arg2 $arg3 $arg4

Related

Arguments in Powershell Script [duplicate]

This question already has an answer here:
dotnet ef scaffold Unrecognized option '-t firstTable -t secondTable' - pass arguments stored in a string
(1 answer)
Closed yesterday.
I try to manipulate pictures with imageick. On the CLI I use this working fine command:
C:\ProgrammeNoSetup\ImageMagick-7.1.0-62-portable-Q16-HDRI-x64\magick.exe D:\orG\3.08_10-02_1.jpg -resize 1200x1200 D:\orG\output\3.08_10-02_1.jpg
But I try to that in a powershell script (test.ps1) with this code:
$CMD = 'C:\ProgrammeNoSetup\ImageMagick-7.1.0-62-portable-Q16-HDRI-x64\magick.exe'
$arg2 = 'D:\orG\3.08_10-02_1.jpg'
$arg3 = '-resize 1200x1200'
$arg4 = 'D:\orG\output\3.08_10-02_1.jpg'
& $CMD $arg2 $arg3 $arg4
Im getting this error: magick.exe: unrecognized option `-resize 1200x1200' at CLI arg 2 # fatal/magick-cli.c/ProcessCommandOptions/659.
I have also tried:
$CMD = 'C:\ProgrammeNoSetup\ImageMagick-7.1.0-62-portable-Q16-HDRI-x64\magick.exe'
$arg1 = 'convert'
$arg2 = 'D:\orG\3.08_10-02_1.jpg'
$arg3 = '-resize 1200x1200'
$arg4 = 'D:\orG\output\3.08_10-02_1.jpg'
& $CMD $arg1 $arg2 $arg3 $arg4
But the error is similar: convert: unrecognized option `-resize 1200x1200' # error/convert.c/ConvertImageCommand/2686.
If I remove the option "-resize 1200x1200". There is now error message and the command is writing the file (without resize) to the output folder. So I think, that I have a problem with my option, but I can't find it. I have invested several hours and als tried with the #-symbol for arguments, without success.
You have to separate argument name and value, otherwise -resize 1200x1200 will be passed as a single token, but native executables usually expect argument name and value to be separate tokens (unless the syntax is without whitespace, e. g. -name:value).
$CMD = 'C:\ProgrammeNoSetup\ImageMagick-7.1.0-62-portable-Q16-HDRI-x64\magick.exe'
$arg1 = 'convert'
$arg2 = 'D:\orG\3.08_10-02_1.jpg'
$arg3 = '-resize', '1200x1200'
# |<-- inserted comma here
$arg4 = 'D:\orG\output\3.08_10-02_1.jpg'
& $CMD $arg1 $arg2 $arg3 $arg4
This turns $arg3 into an array of two strings, which PowerShell passes as separate argument tokens. This is also called splatting and is only done when calling native executables (for PowerShell commands you have to use the # splatting operator).
Another, more concise way:
$CMD = 'C:\ProgrammeNoSetup\ImageMagick-7.1.0-62-portable-Q16-HDRI-x64\magick.exe'
# Create an array of arguments
$imArgs = #(
'convert'
'D:\orG\3.08_10-02_1.jpg'
'-resize', '1200x1200'
'D:\orG\output\3.08_10-02_1.jpg'
)
# Call native command, which splats argument array.
& $CMD $imArgs
# Alternatively you can be explicit about splatting:
& $CMD #imArgs
Make sure you don't name the variable $args which is a reserved PowerShell variable.
As an aside, if you want to be able to call ImageMagick without having to hardcode its path in all of your scripts, add the installation directory of ImageMagick ("C:\ProgrammeNoSetup\ImageMagick-7.1.0-62-portable-Q16-HDRI-x64") to the PATH environment variable.
You could then call ImageMagick simply by specifying the name of its executable:
magick #imArgs

Problem Executing NirSoft SearchMyFiles.exe from Powershell

I know this is a problem in how I'm passing the arguments but I can't figure it out as it looks like I've successfully escaped the characters that might cause a problem.
PS> $ExecutionPath = "G:\BEKDocs\NonInstPrograms\NirSoftx64"
$PgmName = "Searchmyfiles.exe"
$RunCmd = Join-Path -Path "$ExecutionPath" -ChildPath "$PgmName"
$MyArgs = " `/config `"G:\BEKDocs\TestSMF.cfg`" `/StartSearch `/ExplorerCopy `/stext `"G:\BEKDocs\TestSMF.txt`""
$runcmd += $MyArgs
& $Runcmd
---Results: No file Created no Error messages displayed---
--- Show the Created Command ---
PS> $RunCmd
G:\BEKDocs\NonInstPrograms\NirSoftx64\Searchmyfiles.exe /config "G:\BEKDocs\TestSMF.cfg" /StartSearch /ExplorerCopy /stex
t "G:\BEKDocs\TestSMF.txt"
--- Try to Execute the command from History ---
PS> G:\BEKDocs\NonInstPrograms\NirSoftx64\Searchmyfiles.exe /config "G:\BEKDocs\TestSMF.cfg" /StartSearch /ExplorerCopy /stex
t "G:\BEKDocs\TestSMF.txt"
--- Result: No file created no Error messages displayed. ---
--- Type the command by hand ---
PS> G:\BEKDocs\NonInstPrograms\NirSoftx64\searchmyfiles.exe /config "G:\BEKDocs\TestSMF.cfg" /StartSearch /ExplorerCopy /stext "G:\BEKDocs\TestSMF.txt"
--- Result: File CREATED as expected ---
PS>
I'm at a loss!
In testing it appears that it is treating $Runcmd — both executable path and parameters — as one complete executable path to execute. I believe this is explained by the following section of about_Operators...
The call operator does not parse strings. This means that you cannot use command parameters within a string when you use the call operator.
PS> $c = "Get-Service -Name Spooler"
PS> $c
Get-Service -Name Spooler
PS> & $c
& : The term 'Get-Service -Name Spooler' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Instead, pass the executable path and parameters to the call operator separately...
$ExecutionPath = "G:\BEKDocs\NonInstPrograms\NirSoftx64"
$PgmName = "Searchmyfiles.exe"
$RunPath = Join-Path -Path "$ExecutionPath" -ChildPath "$PgmName"
$MyArgs = #(
'/config', '"G:\BEKDocs\TestSMF.cfg"',
'/StartSearch',
'/ExplorerCopy',
'/stext', '"G:\BEKDocs\TestSMF.txt"'
)
& $RunPath $MyArgs
You'll notice that $MyArgs is now an array and not a [String]. It seems that if $MyArgs is a [String] or a single-element array it gets passed to the executable as one parameter surrounded by double quotes. Stored as above each array element gets passed as a parameter with no additional quoting. If you still want to define $MyArgs using one line of text you could do so like this...
$MyArgsText = '/config "G:\BEKDocs\TestSMF.cfg" /StartSearch /ExplorerCopy /stext "G:\BEKDocs\TestSMF.txt"'
# NOTE: This only works because the path parameters contain no spaces
$MyArgs = $MyArgsText -split ' '
All of the above is why, for anything but ad hoc commands, I would prefer the self-documenting, obvious-as-to-which-string-is-treated-as-which nature of a Start-Process call with explicitly-named parameters over the call operator. Given...
$ExecutionPath = "G:\BEKDocs\NonInstPrograms\NirSoftx64"
$PgmName = "Searchmyfiles.exe"
$RunPath = Join-Path -Path "$ExecutionPath" -ChildPath "$PgmName"
$MyArgsText = '/config "G:\BEKDocs\TestSMF.cfg" /StartSearch /ExplorerCopy /stext "G:\BEKDocs\TestSMF.txt"'
...then both this...
Start-Process -FilePath $RunPath -ArgumentList $MyArgsText
...and this...
# NOTE: This only works because the path parameters contain no spaces
$MyArgs = $MyArgsText -split ' '
Start-Process -FilePath $RunPath -ArgumentList $MyArgs
...execute $RunPath with the same parameters.
I think every time I tried to include both the EXE name and the parameters in the same string, The call operator (&) fails. With that in mind, try something where $Runcmd is pointing only to the EXE and nothing else. This also makes testing easy by temporarily placing the path to EchoArgs in $Runcmd to view the actual parameters the EXE will be receiving.
This code example uses the Stop-parsing token (--%) and environmental variables to build the parameters passed to the EXE in $Runcmd.
$ExecutionPath = "G:\BEKDocs\NonInstPrograms\NirSoftx64"
$PgmName = "Searchmyfiles.exe"
$RunCmd = Join-Path -Path "$ExecutionPath" -ChildPath "$PgmName"
$Env:Config = '"G:\BEKDocs\TestSMF.cfg"'
$Env:SText = '"G:\BEKDocs\TestSMF.txt"'
& $Runcmd --% /config %Config% /StartSearch /ExplorerCopy /stext %SText%

How to call a powershell script in vbscript?

I'm trying to call a powershell script in-between one of my project steps in Visual Build.
I've created a new script within visual build and having that call my powershell script.
I selected vbscript and this is the code within the script:
Dim paths, source1
paths = "C:\Dev\"
source1 = "\\10.156.3.14\win"
sCmd = "powershell.exe -noexit -ExecutionPolicy Unrestricted -file C:\Dev\downloadfiles.ps1 -target """ & paths & """ -source """ & source1 & """"
Set xShell = CreateObject("Wscript.Shell")
rReturn = xShell.Run(sCmd, 0, true)
The script timeouts my build.
The powershell script works fine when ran through the console.
Is there something I'm missing?
download.files.ps1 paramaters:
param (
[string[]]$target,
[string[]]$source
)
Additionally is there any way I could see the console output whilst it's running. Even with "-noexit" I'm seeing nothing.
Update --
The first part of the script runs and returns some of the relevant files.
Although the part that takes in the parameters are not functioning.
This seems to be the better alternative as the script is now taking in parameters :
Set objShell = CreateObject("Wscript.Shell")
objShell.run("powershell.exe -noexit -ExecutionPolicy Unrestricted -file .\downloadfiles.ps1 -target """ & paths & """ -source """ & source1 & """")
Follow up question. How would I go about passing in a string arrray through the vbscript call?
e.g
$target = #('c:\dev','d:\lib')
When using -File, I'm afraid all array elements in $target will be forwarded to the PowerShell script as a single string.
Try
VbScript
Option Explicit
'I hate writing """something""" or Chr(34) & "something" & Chr(34)
'all the time, so I use this little helper function
Private Function Quote(text)
Quote = Chr(34) & text & Chr(34)
End Function
Dim paths, source1, script, sCmd, objShell
'join the quoted path elements with a semi-colon
paths = Join(Array(Quote("C:\Dev"), Quote("D:\lib")), ";")
source1 = Quote("\\10.156.3.14\win")
script = Quote("D:\Test\downloadfiles.ps1")
sCmd = "powershell.exe -NoExit -NoLogo -ExecutionPolicy Unrestricted -File " & script & " -target " & paths & " -source " & source1
Set objShell = CreateObject("Wscript.Shell")
objShell.run(sCmd)
Test with PowerShell
downloadfiles.ps1
param (
[string[]]$target,
[string[]]$source
)
$target = $target | ForEach-Object { $_ -split ';' }
$source = $source | ForEach-Object { $_ -split ';' }
Write-Host "Elements in target: $($target.Count)"
Write-Host "Elements in source: $($source.Count)"
Write-Host
for ($i = 0; $i -lt $target.Count; $i++) {
'$target[{0}]: {1}' -f $i, $target[$i]
}
Write-Host
for ($i = 0; $i -lt $source.Count; $i++) {
'$source[{0}]: {1}' -f $i, $source[$i]
}
Output in PowerShell console:
Elements in target: 2
Elements in source: 1
$target[0]: C:\Dev
$target[1]: D:\lib
$source[0]: \\10.156.3.14\win

PowerShell variable to batch issue [duplicate]

I'm trying to use Log Parser within PowerShell to export a Windows Evtx log file to CSV:
$logparser = "c:\program files (x86)\Log Parser 2.2\logparser.exe"
$allArgs = ("SELECT * INTO c:\logs\logs.csv FROM c:\logs\logs.evtx", "-i:evt", "-o:csv")
$ps = Start-Process -FilePath $logparser -ArguementList $allArgs -Wait -Passthru -NoNewWindow;
$ps.WaitForExit()
$ps.ExitCode;
But when I run this I get an error:
Error: detected extra argument "*" after query
The error code is 13. I tried putting the paths in single quotes and running it from the same directory as the logs but it keeps returning the same error.
You need to preserve the double quotes around the query string, otherwise it won't be recognized as a single argument by the spawned process.
Putting the query string (with double quotes) in single quotes might work:
$allArgs = '"SELECT * INTO c:\logs\logs.csv FROM c:\logs\logs.evtx"',
"-i:evt",
"-o:csv"
However, a much simpler solution to the problem would be to avoid Start-Process entirely and use the call operator (&) instead:
$logparser = "c:\program files (x86)\Log Parser 2.2\logparser.exe"
$query = "SELECT * INTO c:\logs\logs.csv FROM c:\logs\logs.evtx"
& $logparser -i:evt -o:csv $query

Logparser error when used with PowerShell

I'm trying to use Log Parser within PowerShell to export a Windows Evtx log file to CSV:
$logparser = "c:\program files (x86)\Log Parser 2.2\logparser.exe"
$allArgs = ("SELECT * INTO c:\logs\logs.csv FROM c:\logs\logs.evtx", "-i:evt", "-o:csv")
$ps = Start-Process -FilePath $logparser -ArguementList $allArgs -Wait -Passthru -NoNewWindow;
$ps.WaitForExit()
$ps.ExitCode;
But when I run this I get an error:
Error: detected extra argument "*" after query
The error code is 13. I tried putting the paths in single quotes and running it from the same directory as the logs but it keeps returning the same error.
You need to preserve the double quotes around the query string, otherwise it won't be recognized as a single argument by the spawned process.
Putting the query string (with double quotes) in single quotes might work:
$allArgs = '"SELECT * INTO c:\logs\logs.csv FROM c:\logs\logs.evtx"',
"-i:evt",
"-o:csv"
However, a much simpler solution to the problem would be to avoid Start-Process entirely and use the call operator (&) instead:
$logparser = "c:\program files (x86)\Log Parser 2.2\logparser.exe"
$query = "SELECT * INTO c:\logs\logs.csv FROM c:\logs\logs.evtx"
& $logparser -i:evt -o:csv $query