I am new to PowerShell and I am trying to get a script to work to list my parallel ports. I took the PowerShell script from here:
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_ParallelPort")
For Each objItem in colItems
Wscript.Echo "Availability: " & objItem.Availability
For Each strCapability in objItem.Capabilities
Wscript.Echo "Capability: " & strCapability
Next
Wscript.Echo "Description: " & objItem.Description
Wscript.Echo "Device ID: " & objItem.DeviceID
Wscript.Echo "Name: " & objItem.Name
Wscript.Echo "OS Auto Discovered: " & objItem.OSAutoDiscovered
Wscript.Echo "PNP Device ID: " & objItem.PNPDeviceID
Wscript.Echo "Protocol Supported: " & objItem.ProtocolSupported
Next
After executing the script I am getting:
PS C:\> .\script.ps1
Unexpected token '_' in expression or statement.
At C:\script.ps1:4 char:44
+ Set objWMIService = GetObject("winmgmts:" _ <<<<
+ CategoryInfo : ParserError: (_:String) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
I even tried changing & by $ as I can see in this script which also doesn't work. Is a problem with my PowerShell or is the script which is causing the problem?
PS: I am using PowerShell v2.0 in Windows XP 32bit
Thank you in advance!
EDIT:
According to the answer so it isn't a PowerShell script but a vbscript. So my question now would be why this script doesn't work if it is indeed a PowerShell Script:
$strComputer = "."
$colItems = get-wmiobject -class "Win32_ParallelPort" -namespace "root\CIMV2" `
-computername $strComputer
foreach ($objItem in $colItems) {
write-host "Availability: " $objItem.Availability
write-host "Capabilities: " $objItem.Capabilities
write-host "Capability Descriptions: " $objItem.CapabilityDescriptions
write-host "Caption: " $objItem.Caption
write-host "Configuration Manager Error Code: " $objItem.ConfigManagerErrorCode
write-host "Configuration Manager User Configuration: " $objItem.ConfigManagerUserConfig
write-host "Creation Class Name: " $objItem.CreationClassName
write-host "Description: " $objItem.Description
write-host "Device ID: " $objItem.DeviceID
write-host "DMA Support: " $objItem.DMASupport
write-host "Error Cleared: " $objItem.ErrorCleared
write-host "Error Description: " $objItem.ErrorDescription
write-host "Installation Date: " $objItem.InstallDate
write-host "Last Error Code: " $objItem.LastErrorCode
write-host "Maximum Number Controlled: " $objItem.MaxNumberControlled
write-host "Name: " $objItem.Name
write-host "Operating System Auto-Discovered: " $objItem.OSAutoDiscovered
write-host "PNP DeviceID: " $objItem.PNPDeviceID
write-host "Powe rManagement Capabilities: " $objItem.PowerManagementCapabilities
write-host "Power Management Supported: " $objItem.PowerManagementSupported
write-host "ProtocolS upported: " $objItem.ProtocolSupported
write-host "Status: " $objItem.Status
write-host "Status Information: " $objItem.StatusInfo
write-host "System Creation Class Name: " $objItem.SystemCreationClassName
write-host "System Name: " $objItem.SystemName
write-host "Time Of Last Reset: " $objItem.TimeOfLastReset
write-host
}
I am getting this error:
Missing expression after unary operator '-'.
At C:\script.ps1:4 char:2
+ - <<<< computername $strComputer
+ CategoryInfo : ParserError: (-:String) [], ParseException
+ FullyQualifiedErrorId : MissingExpressionAfterOperator
In your revised script, there's a space after the backtick on line 3, so the continuation isn't being recognized. When you use the backtick to for a line continuation in PowerShell, it can't be followed by a whitespace character. Eliminate that space, or make it all one line:
$colItems = get-wmiobject -class "Win32_ParallelPort" -namespace "root\CIMV2" -computername $strComputer
Your example script is not PowerShell, it's vbscript.
PowerShell is much simpler, you would use something like:
Get-WmiObject Win32_ParallelPort
Related
Working on this for over 2 weeks and I'm run out of ideas.
Hoping for some1 experienced with dockerized Sitecore.
I have a Sitecore Docker (windows container) build and i'm trying to run script on it.
Sitecore is built with this tutorial: http://rockpapersitecore.com/2019/10/yet-another-sitecore-docker-series/
Script:
Write-Host "Preparing for DB upgrade"
Import-Module C:\automation\SPE
$session = New-ScriptSession -Username admin -Password b -ConnectionUri http://localhost
$jobId = Invoke-RemoteScript -Session $session -ScriptBlock {
Install-Package -Path C:\automation\CT_DB_upgrade.zip -InstallMode Merge -MergeMode Merge
} -AsJob
Start-Sleep -s 5
Wait-RemoteScriptSession -Session $session -Id $jobId -Delay 5 -Verbose
Write-Host "CT_DB_upgrade.zip installed"
Stop-ScriptSession -Session $session
More over script suppose to update clean DB with tables for our Sitecore connector.
Script works fine, tables are added and Sitecore works, but...script times out..
After "CT_DB_upgrade.zip installed" it runs for about 2min and times out.
Normally on VM script runs for about 0.5/ 1 sec and doesn't crash.
PS C:\automation> .\install-ct-db.ps1
Preparing for DB upgrade
VERBOSE: Checking the Runspace for the variable id.
VERBOSE: Preparing to invoke the script against the service at url
http://localhost/-/script/script/?sessionId=2ca051be-195d-4f0a-90b7-d084b9246ca3&rawOutput=False&persistentSession=F alse
VERBOSE: Transferring script to server
VERBOSE: Script transfer complete.
VERBOSE: Polling job 55ed096e-16ae-49cd-8d20-4d6a4ec219d1. Status : Available.
VERBOSE: Finished polling job 55ed096e-16ae-49cd-8d20-4d6a4ec219d1.
VERBOSE: Checking the Runspace for the variable id.
VERBOSE: Preparing to invoke the script against the service at url
http://localhost/-/script/script/?sessionId=2ca051be-195d-4f0a-90b7-d084b9246ca3&rawOutput=False&persistentSession=F alse
VERBOSE: Transferring script to server
VERBOSE: Script transfer complete.
CT_DB_upgrade.zip installed
Exception calling "Invoke" with "1" argument(s): "The operation has timed out"
At C:\automation\SPE\ConvertFrom-CliXml.ps1:24 char:9
+ $deserializer = $ctor.Invoke($xr)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Exception calling "InvokeMember" with "5" argument(s): "Non-static method requires a target."
At C:\automation\SPE\ConvertFrom-CliXml.ps1:26 char:16
+ ... while (!$type.InvokeMember("Done", "InvokeMethod,NonPublic,Insta ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : TargetException
As i understand it crashes at: Stop-ScriptSession -Session $session.
I have tried changing different web.config settings, like timeouts, but even if i set timeout after 10min it will timeout anyway after around 2min.
Here is ConvertFrom-CliXml.ps1:
function ConvertFrom-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$InputObject
)
begin
{
$OFS = "`n"
[String]$xmlString = ""
}
process
{
$xmlString += $InputObject
}
end
{
#This try catch ignores rest of the code and let script finish with no error.
#try {
$type = [PSObject].Assembly.GetType('System.Management.Automation.Deserializer')
$ctor = $type.GetConstructor('instance,nonpublic', $null, #([xml.xmlreader]), $null)
$sr = New-Object System.IO.StringReader $xmlString
$xr = New-Object System.Xml.XmlTextReader $sr
$deserializer = $ctor.Invoke($xr)
$done = $type.GetMethod('Done', [System.Reflection.BindingFlags]'nonpublic,instance')
while (!$type.InvokeMember("Done", "InvokeMethod,NonPublic,Instance", $null, $deserializer, #()))
{
try {
$type.InvokeMember("Deserialize", "InvokeMethod,NonPublic,Instance", $null, $deserializer, #())
} catch {
Write-Warning "Could not deserialize ${string}: $_"
}
}
$xr.Close()
$sr.Dispose()
#} catch {
# Write-Host "Could not finish script correctly"
<#
.SYNOPSIS
Short description
.DESCRIPTION
Long description
.PARAMETER InputObject
Parameter description
.EXAMPLE
An example
.NOTES
General notes
#>
}
}
I builded Jenkins with parameters in my configuration:
a = a$
b = b$$
c = c$$$
d = d$$$$
e = e$e$e$e$
I builded my pipeline and it contained this possibilities how to display content of environment variables:
sh """
echo "${env.a}"
echo "\$a"
echo "${env.b}"
echo "\$b"
echo "${env.c}"
echo "\$c"
echo "${env.d}"
echo "\$d"
echo "${env.e}"
echo "\$e"
"""
It returned:
+ echo 'a$'
a$
+ echo 'a$$'
a$$
+ echo 'b$'
b$
+ echo 'b$$'
b$$
+ echo c14
c14
+ echo 'c$$$$'
c$$$$
+ echo d14
d14
+ echo 'd$$$$'
d$$$$
+ echo 'eeee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$14'
eeee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$14
+ echo 'ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$'
ee$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$e$$$$
Anyone who can explain this behaviour?
First of all - very interesting problem. Results are... unusual :)
I couldn't reproduce 100% of your results on my Jenkins, it's probably version/platform dependent. But fortunately the most interesting parameter e returned all that mess. So I'll focus on in.
It looks like parameters are evaluated before they are passed to environment. So each occurrence of $e is replaced by current value of e variable (which is e$e$e$e$ so far). So, we have e then three times $e replaced by e$e$e$e$ and finally $. The result is: e e$e$e$e$ e$e$e$e$ e$e$e$e$ $ (spaces added for readability). And this is value stored in environment. You can see it printed by your last echo (but with every $ replaced by $$).
The longest output (echo "${env.e}") doesn't do anything new - it just takes ee$e$e$e$e$e$e$e$e$e$e$e$$ and evaluates it one more time, replacing every occurrence of $e by ee$e$e$e$e$e$e$e$e$e$e$e$$. And finally, replaces every $ by $$ when printing :)
Jenkins GitHub pull request builder for execute shell, all the below are coming blank.
echo 'ghprbActualCommit: ' $ghprbActualCommit
echo 'ghprbActualCommitAuthor: ' $ghprbActualCommitAuthor
echo 'ghprbActualCommitAuthorEmail: ' $ghprbActualCommitAuthorEmail
echo 'ghprbPullDescription: ' $ghprbPullDescription
echo 'ghprbPullId: ' $ghprbPullId
echo 'ghprbPullLink: ' $ghprbPullLink
echo 'ghprbPullTitle: ' $ghprbPullTitle
echo 'ghprbSourceBranch: ' $ghprbSourceBranch
echo 'ghprbTargetBranch: ' $ghprbTargetBranch
echo 'sha1: ' $sha1
I am able to get these values in the job which is triggered on pull request:) Earlier I was trying to get these values in a job which was getting triggered post merge request.
I'm trying to use a Groovy script (to run with jenkins-cli.jar) to verify some git information.
To this end, I have the following simple groovy script:
def getBranchSha = { branch ->
def wd = new File('/my/git/repo');
def sout = new StringBuffer(), serr = new StringBuffer();
def gitcmd = 'git show-ref ' + branch + ' --hash';
def proc = gitcmd.execute(null, wd);
proc.consumeProcessOutput(sout, serr);
proc.waitFor();
def sha = sout.toString().trim();
out.println("exitCode: " + proc.exitValue() + "\terror: " + serr.toString());
out.println("input: " + branch + "\toutput: \"" + sha + "\"");
assert sha.equals("10d94325c8fc1050f3e362d2fbb9f9041e6b9360");
}
getBranchSha("origin/master");
I expect this to construct a command line git show-ref origin/master --hash and execute that in the working dir of my git repo. I expect the output of this to be the current SHA of my origin/master branch in this repo 10d94325c8fc1050f3e362d2fbb9f9041e6b9360, and the code asserts this to be the case.
Most of the time, this code runs exactly as expected, but sometimes for no reason I can see, the output is blank:
> while [ $? -eq 0 ] ; do java -jar jenkins-cli.jar -s http://localhost:8080 groovy tst.groovy ; done
exitCode: 0 error:
input: origin/master output: "10d94325c8fc1050f3e362d2fbb9f9041e6b9360"
exitCode: 0 error:
input: origin/master output: "10d94325c8fc1050f3e362d2fbb9f9041e6b9360"
...
exitCode: 0 error:
input: origin/master output: "10d94325c8fc1050f3e362d2fbb9f9041e6b9360"
exitCode: 0 error:
input: origin/master output: ""
java.lang.SecurityException: Rejected: org.codehaus.groovy.runtime.powerassert.PowerAssertionError
at hudson.remoting.ClassFilter.check(ClassFilter.java:20)
at hudson.remoting.MultiClassLoaderSerializer$Input.resolveClass(MultiClassLoaderSerializer.java:111)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1612)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1517)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at hudson.remoting.UserRequest.deserialize(UserRequest.java:184)
at hudson.remoting.UserResponse.retrieve(UserRequest.java:217)
at hudson.remoting.Channel.call(Channel.java:781)
at hudson.remoting.RemoteInvocationHandler.invoke(RemoteInvocationHandler.java:250)
at com.sun.proxy.$Proxy3.main(Unknown Source)
at hudson.cli.CLI.execute(CLI.java:338)
at hudson.cli.CLI._main(CLI.java:509)
at hudson.cli.CLI.main(CLI.java:390)
Based on the zero exit code, I assume that the command has executed normally, but I don't understand why the output hasn't been received. I thought that it might be because I don't understand how waitFor is supposed to work, but I've tried placing the proc.waitFor() line at various points in the function with no difference.
Running a similar script to verify that "pwd".execute().text.trim().equals("/") seems to always return correctly.
Any ideas?
I found a way that works. Rather than calling waitFor and consumeProcessOutput one after the other (in any order), the method waitForProcessOutput will reliably deliver the shell output to my groovy script.
def getBranchSha = { branch ->
def wd = new File('/my/git/repo');
def sout = new StringBuffer(), serr = new StringBuffer();
def gitcmd = 'git show-ref ' + branch + ' --hash';
def proc = gitcmd.execute(null, wd);
proc.waitForProcessOutput(sout, serr);
def sha = sout.toString().trim();
out.println("exitCode: " + proc.exitValue() + "\terror: " + serr.toString());
out.println("input: " + branch + "\toutput: \"" + sha + "\"");
assert sha.equals("10d94325c8fc1050f3e362d2fbb9f9041e6b9360");
}
getBranchSha("origin/master");
This code will give me what I want. I don't understand why a combination of waitFor and consumeProcessOutput doesn't do the same thing though.
I am setting CI for .Net project using Jenkins.
I used MSTest Plugin and VStestrunner plugin to run test.
Now I have .trx file and .Coverage file
I am facing problem in displaying code coverage report
Please help me is you know any plugin to do this.
I have struggled this for a long time, finally I found we can use "CodeCoverage.exe" "ReportGenarator.exe" and "Cobertura plugin" to show perfect coverage report.
"ReportGenarator.exe" can be get from https://github.com/danielpalme/ReportGenerator/releases
first use "CodeCoverage.exe" translate .coverage file to .xml file
"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Dynamic Code Coverage Tools\CodeCoverage.exe" analyze -output:./TestResults/coverage.xml ./TestResults/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.coverage"
second use ReportGenarator.exe translate vstest xml format to Cobertura xml format
"ReportGenerator_4.4.7\net47\ReportGenerator.exe" -reports:./TestResults/coverage.xml -targetdir:./TestResults -reporttypes:cobertura
finally install cobertura plugin use it to collect xml file, here give a pipeline useage example
post {
always {
cobertura coberturaReportFile: './TestResults/Cobertura.xml'
}
}
the result just like this
To display the coverage report you need to convert it in XML format and use MSTest Plugin to publish the report. MSTest Plugin recommends (https://wiki.jenkins-ci.org/display/JENKINS/MSTest+Plugin) to use third party application to convert in XML format and powershell (you will need to install pugin for it) to run it.
However you can convert it with PowerShell only. There is example of script:
$coverageFile = $(get-ChildItem -Path .\TestResults -Recurse -Include *coverage)[0]
$xmlCoverageFile = ".\TestResults\vstest.coveragexml"
Add-Type -path "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies\Microsoft.VisualStudio.Coverage.Analysis.dll"
[string[]] $executablePaths = #($coverageFile)
[string[]] $symbolPaths = #()
$info = [Microsoft.VisualStudio.Coverage.Analysis.CoverageInfo]::CreateFromFile($coverageFile, $executablePaths, $symbolPaths);
$data = $info.BuildDataSet()
$data.WriteXml($xmlCoverageFile)
You maybe will need to fix the path to Microsoft.VisualStudio.Coverage.Analysis.dll according to your VS version.
Following ghking's answer, cobertura complains that the xml is not found although it's on the disk. I have to remove './' from the path, so that cobertura is able to find the file.
post {
always {
cobertura coberturaReportFile: 'TestResults/Cobertura.xml'
}
}
The complete script to do this is:
<#
.SYNOPSIS
Script to convert code coverage report into xml format that can then be published by external tools.
.DESCRIPTION
Covering code coverage statistics as part of quality improvement initiatives.
#>
Param(
[String] $InputCoveragePath =#("..\GeneratedFiles\Docs\Reports"),
[String] $OutputCoverageFileExtension =#(".coveragexml"),
[String] $CoverageAnalysisAssembly =#("Microsoft.VisualStudio.Coverage.Analysis.dll"),
[String[]] $ExecutablePaths =#(""),
[String[]] $SymbolPaths =#("")
)
$ScriptLocation = Split-Path $script:MyInvocation.MyCommand.Path -Parent
Write-Host $ScriptLocation
$RunAs32Bit = {
Param(
[String] $InputCoveragePath =#("..\GeneratedFiles\Docs\Reports"),
[String] $OutputCoverageFileExtension =#(".coveragexml"),
[String] $CoverageAnalysisAssembly =#("Microsoft.VisualStudio.Coverage.Analysis.dll"),
[String[]] $ExecutablePaths =#(""),
[String[]] $SymbolPaths =#(""),
[String] $ScriptLocation =#(".")
)
Write-Host "[CoverageConverter][Begin]: Coverage conversion started..."
Write-Host "[CoverageConverter][InputCoveragePath]: $InputCoveragePath"
Write-Host "[CoverageConverter][OutputCoverageFileExtension]: $OutputCoverageFileExtension"
Write-Host "[CoverageConverter][CoverageAnalysisAssembly]: $CoverageAnalysisAssembly"
Write-Host "[CoverageConverter][ExecutablePaths]: $ExecutablePaths"
Write-Host "[CoverageConverter][SymbolPaths]: $SymbolPaths"
Write-Host "[CoverageConverter][ScriptLocation]: $ScriptLocation"
Add-Type -path "$CoverageAnalysisAssembly"
$Result = 0
if($InputCoveragePath -and (Test-Path "$InputCoveragePath") )
{
[string[]] $coverageFiles = $(Get-ChildItem -Path $InputCoveragePath -Recurse -Include *coverage)
#($coverageFiles) | ForEach-Object {
$coverageFile = $_
$coverageFileOut = (Join-Path -Path $(Split-Path $_ -Parent) -ChildPath ($(Get-Item $_).BaseName + "$OutputCoverageFileExtension"))
Write-Host "If all OK the xml will be written to: $coverageFileOut"
$info = [Microsoft.VisualStudio.Coverage.Analysis.CoverageInfo]::CreateFromFile($coverageFile, $ExecutablePaths, $SymbolPaths);
if($info){
$data = $info.BuildDataSet()
$data.WriteXml($coverageFileOut)
}
}
}
else
{
Write-Host "Please specify a valid input coverage file."
$Result = 1
}
Write-Host "[CoverageConverter][End]: Coverage conversion completed with result $Result"
return $Result
}
#Run the code in 32bit mode if PowerShell isn't already running in 32bit mode
If($env:PROCESSOR_ARCHITECTURE -ne "x86"){
Write-Warning "Non-32bit architecture detected, processing original request in separate 32bit process."
$Job = Start-Job $RunAs32Bit -RunAs32 -ArgumentList ($InputCoveragePath, $OutputCoverageFileExtension, $CoverageAnalysisAssembly, $ExecutablePaths, $SymbolPaths, $ScriptLocation)
$Result = $Job | Wait-Job | Receive-Job
}Else{
$Result = Invoke-Command -ScriptBlock $RunAs32Bit -ArgumentList ($InputCoveragePath, $OutputCoverageFileExtension, $CoverageAnalysisAssembly, $ExecutablePaths, $SymbolPaths, $ScriptLocation)
}