Note: The actual error from Java/Closure Compiler came from the missing t in --js-outputfile!
I have this PowerShell script:
cls
$jsFiles = #();
Get-ChildItem | Where {$_.PsIsContainer} | Foreach {
$dir = $_.FullName;
$jsFile = $dir + "\" + $_.Name + ".js";
if (Test-Path ($jsFile)) {
$jsFiles += $jsFile;
}
}
$wd = [System.IO.Directory]::GetCurrentDirectory();
# Build Closure Compiler command line call
$cmd = #("-jar $wd\..\ClosureCompiler\compiler.jar");
Foreach ($file in $jsFiles) {
# Both insert a newline!
$cmd += "--js $file";
#$cmd = "$cmd --js $file";
}
$cmd = "$cmd --js_ouput_file $wd\all.js";
Invoke-Expression "java.exe $cmd"
The problem is that newlines are inserted on each += or $cmd = "$cmd str" call!
Echoargs gives me this output:
Arg 0 is <-jar>
Arg 1 is <S:\ome\Path\compiler.jar>
Arg 2 is <--js>
Arg 3 is <S:\ome\Path\script1.js>
Arg 4 is <--js>
Arg 5 is <S:\ome\Path\script2.js>
...
Arg 98 is <--js_ouput_file>
Arg 99 is <S:\ome\Path\all.js>
(Possibly) therefore, I get some errors from java.exe:
java.exe : "--js_ouput_file" is not a valid option
At line:1 char:1
+ java.exe -jar ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: ("--js_ouput_file" is not a valid option:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Try to rewrite to much simple version:
cls
$wd = [System.IO.Directory]::GetCurrentDirectory();
# Build Closure Compiler command line call
$cmd = "-jar $wd\..\ClosureCompiler\compiler.jar";
$arrayOfJs = Get-ChildItem -Recurse -Include "*.js" | % { "--js $_.FullName" };
$cmd += [string]::Join(" ", $arrayOfJs);
Invoke-Expression "java $cmd --js_ouput_file $wd\all.js"
When you do
$cmd = #(...);
you are creating an array and hence the subsequent += on it is appending elements to the array and is not string concatenation. Just have it as a string, or before using $cmd. Do something like:
$cmd -join " "
Which will join together the elements into a single space-separated string. By default when the array is coerced into a string, you will see new lines between the elements.
Related
I am working on a method of reading UninstallStrings for software from the registry. And then I'm trying to execute those strings to uninstall the software.
When I print out the variables that hold the string info, it prints the whole string (with the arguments) correctly, but I am unable to run those strings.
There are multiple parts to this issue.
Some install strings are formatted like so
c:\file path\blah\app.exe /uninstall
"c:\file path\blah\app.exe" /uninstall
c:\file path\blah\app.exe --uninstall
'c:\file path\blah\app.exe' /uninstall
What I'm trying to do is figure out the best way to be able to run the uninstaller in a "universal" way.
Is there a way to do this effectively?
I tried executing the strings 2 different ways.
& $uninstaller
and
Start-Process -FilePath cmd.exe -ArgumentList '/c', $uninstaller -Wait
Neither of them seem to work. No errors, but they don't seem to run because when I check the app it's still installed.
And I tried splitting the text a few ways.
$Uninstaller.split("/")[0]
$Uninstaller.split("/",2)[1]
$($Uninstaller) | Invoke-Expression
$Uninstaller.Substring(0,$Uninstaller.lastIndexOf('.exe '))
$Uninstaller.split('^(*?\.exe) *')
Thanks in advance!
Try the following testing script, where simple console application CliParser.exe merely echoes command line arguments (written in C, inspired here). Used the exact copy with a space in name CliParser noPause.exe; it shows that . $Uninstaller $UninsParams should work even if a path $Uninstaller contains space(s).
No need to use Start-Process -FilePath cmd.exe …; just apply the dot-sourcing operator as . $Uninstaller $UninsParams…
The $lines collection contains an almost representative syntax patterns of uninstall strings (taken from my Windows 10):
$lines = #'
MsiExec.exe /X{FFC6E93A-B9AD-3F20-9B06-EE20E24AAEAF}
"D:\Program Files (x86)\Virtual Russian Keyboard\unins000.exe"
"C:\Windows10Upgrade\Windows10UpgraderApp.exe" /Uninstall
C:\Windows\SysWOW64\msiexec.exe /package {CFEF48A8-BFB8-3EAC-8BA5-DE4F8AA267CE} /uninstall {815F0BC1-7E54-300C-9ACA-C9460FDF6F78} /qb+ REBOOTPROMPT=""
C:\Program Files (x86)\InstallShield Installation Information\{8833FFB6-5B0C-4764-81AA-06DFEED9A476}\Setup.exe -runfromtemp -removeonly
"C:\WINDOWS\SysWOW64\RunDll32.EXE" "C:\Program Files\NVIDIA Corporation\Installer2\InstallerCore\NVI2.DLL",UninstallPackage Display.Driver
%windir%\system32\sdbinst.exe -u "C:\WINDOWS\AppPatch\CustomSDB\{9f4f4a9b-eec5-4906-92fe-d1f43ccf5c8d}.sdb"
'# -split [System.Environment]::NewLine
$FakeUninstaller = "D:\bat\CLIParser noPause.exe"
foreach ( $line in $lines ) {
# $line
$aux = $line -split #('\.exe'),2,[System.StringSplitOptions]::None
$Uninstaller = (cmd /c echo $($aux[0].TrimStart('"').TrimStart("'") + '.exe')).Trim('"')
$UninsParams = $aux[1].TrimStart('"').TrimStart("'").Trim().split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
". $Uninstaller $UninsParams"
. $FakeUninstaller $UninsParams | Where-Object { $_ -notlike "param 0 = *" }
}
Output: D:\PShell\SO\62023960.ps1
. MsiExec.exe /X{FFC6E93A-B9AD-3F20-9B06-EE20E24AAEAF}
param 1 = /X{FFC6E93A-B9AD-3F20-9B06-EE20E24AAEAF}
. "D:\Program Files (x86)\Virtual Russian Keyboard\unins000.exe"
. C:\Windows10Upgrade\Windows10UpgraderApp.exe /Uninstall
param 1 = /Uninstall
. C:\Windows\SysWOW64\msiexec.exe /package {CFEF48A8-BFB8-3EAC-8BA5-DE4F8AA267CE} /uninstall {815F0BC1-7E54-300C-9ACA-C9460FDF6F78} /qb+ REBOOTPROMPT=""
param 1 = /package
param 2 = {CFEF48A8-BFB8-3EAC-8BA5-DE4F8AA267CE}
param 3 = /uninstall
param 4 = {815F0BC1-7E54-300C-9ACA-C9460FDF6F78}
param 5 = /qb+
param 6 = REBOOTPROMPT=""
. "C:\Program Files (x86)\InstallShield Installation Information\{8833FFB6-5B0C-4764-81AA-06DFEED9A476}\Setup.exe" -runfromtemp -removeonly
param 1 = -runfromtemp
param 2 = -removeonly
. C:\WINDOWS\SysWOW64\RunDll32.exe "C:\Program Files\NVIDIA Corporation\Installer2\InstallerCore\NVI2.DLL",UninstallPackage Display.Driver
param 1 = C:\Program Files\NVIDIA Corporation\Installer2\InstallerCore\NVI2.DLL,UninstallPackage
param 2 = Display.Driver
. C:\WINDOWS\system32\sdbinst.exe -u "C:\WINDOWS\AppPatch\CustomSDB\{9f4f4a9b-eec5-4906-92fe-d1f43ccf5c8d}.sdb"
param 1 = -u
param 2 = C:\WINDOWS\AppPatch\CustomSDB\{9f4f4a9b-eec5-4906-92fe-d1f43ccf5c8d}.sdb
Figured it out. Maybe there's a better way to do it, but this seems to work for me.
CLS
$Software = "OneDrive"
$Filter = "*" + $Software + "*"
$Program = $ProgUninstall = $FileUninstaller = $FileArg = $NULL
try
{
if (Test-Path -Path "HKLM:\SOFTWARE\WOW6432Node")
{
$programs = Get-ItemProperty -Path "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" -ErrorAction Stop
}
$programs += Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" -ErrorAction Stop
$programs += Get-ItemProperty -Path "Registry::\HKEY_USERS\*\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" -ErrorAction SilentlyContinue
}
catch
{
Write-Error $_
break
}
foreach($Program in $Programs)
{
$ProgDisplayName = $Program.DisplayName
$ProgUninstall = $Program.UninstallString
if($ProgDisplayName -like $Filter)
{
if($ProgUninstall -like "msiexec*")
{
$FileUninstaller = $ProgUninstall.split(" ")[0]
$FileArg = ($($ProgUninstall).split(" ",2)[1])
}
else
{
if(($ProgUninstall -like '"*"*') -or ($ProgUninstall -like "'*'*"))
{
#String has quotes, don't need to do anything
}
else
{
if($NULL -ne $ProgUninstall)
{
#String doesn't have quotes so we should add them
$ProgUninstall = '"' + ($ProgUninstall.Replace('.exe','.exe"'))
}
}
#Let's grab the uninstaller and arguments
$FileUninstaller = $ProgUninstall.split('"')[1]
$FileArg = $ProgUninstall.split('"')[-1]
}
#Debug
#$FileUninstaller
#$FileArg
#Run the Uninstaller
Start-Process $FileUninstaller -ArgumentList $FileArg -wait -ErrorAction SilentlyContinue
}
}
This works very easily for msi installs:
get-package *whatever* | uninstall-package
Here's a non-msi silent uninstall example, but you have to add "/S" or whatever the silent uninstall option is:
get-package notepad++* |
% { & $_.Meta.Attributes['UninstallString'] /S }
How can I check if a string exists in:
1 text file;
size up until 10GB;
taking into account that the file is only one line;
the file only contains random numbers 1 to 9;
using powershell (because I think it will be more efficient, although I don't know how to program in this language);
I have tried this in batch:
FINDSTR "897516" decimal_output.txt
pause
But as I said I need the faster and more efficient way to do this.
I also tried this code that I have found in stackoverflow:
$SEL = Select-String -Path C:\Users\fabio\Desktop\CONVERTIDOS\dec_output.txt -Pattern "123456"
if ($SEL -ne $null)
{
echo Contains String
}
else
{
echo Not Contains String
}
But I get the error below, and I don't know if this code is the most solid or adequate. The error:
Select-String : Tipo de excepção 'System.OutOfMemoryException' accionado.
At C:\Users\fabio\Desktop\1.ps1:1 char:8
+ $SEL = Select-String -Path C:\Users\fabio\Desktop\CONVERTIDOS\dec_out ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Select-String], OutOfMemoryException
+ FullyQualifiedErrorId : System.OutOfMemoryException,Microsoft.PowerShell.Commands.SelectStringCommand
This should do the job:
#################################################################################################################
#
# Searches for a user defined string in the $input_file and counts matches. Works with files of any size.
#
# Adjust source directory and input file name.
#
$source = "C:\adjust\path"
$input_file = "file_name.extension"
#
#
# Define the string you want to search for. Keep quotation marks even if you only search for numbers (otherwise
# $pattern.Length will be 1 and this script will no longer work with files larger than the $split_size)!
#
$pattern = "Enter the string to search for in here"
#
#
# Using Get-Content on an input file with a size of 1GB or more will cause System.OutOfMemoryExceptions,
# therefore a large file gets temporarily split up.
#
$split_size = 100MB
#
#
# Thanks #Bob (https://superuser.com/a/1295082/868077)
#################################################################################################################
Set-Location $source
if (test-path ".\_split") {
while ($overwrite -ne "true" -and $overwrite -ne "false") {
"`n"
$overwrite = Read-Host ' Splitted files already/still exist! Delete and overwrite?'
if ($overwrite -match "y") {
$overwrite = "true"
Remove-Item .\_split -force -recurse
$a = "`n Deleted existing splitted files!"
} elseif ($overwrite -match "n") {
$overwrite = "false"
$a = "`n Continuing with existing splitted files!"
} elseif ($overwrite -match "c") {
exit
} else {
Write-Host "`n Error: Invalid input!`n Type 'y' for 'yes'. Type 'n' for 'no'. Type 'c' for 'cancel'. `n`n`n"
}
}
}
Clear-Host
if ((Get-Item $input_file).Length -gt $split_size) {
while ($delete -ne "true" -and $delete -ne "false") {
"`n"
$delete = Read-Host ' Delete splitted files afterwards?'
if ($delete -match "y") {
$delete = "true"
$b = "`n Splitted files will be deleted afterwards!"
} elseif ($delete -match "n") {
$delete = "false"
$b = "`n Splitted files will not be deleted afterwards!"
} elseif ($delete -match "c") {
exit
} else {
Write-Host "`n Error: Invalid input!`n Type 'y' for 'yes'. Type 'n' for 'no'. Type 'c' for 'cancel'. `n`n`n"
}
}
Clear-Host
$a
$b
Write-Host `n This may take some time!
if ($overwrite -ne "false") {
New-Item -ItemType directory -Path ".\_split" >$null 2>&1
[Environment]::CurrentDirectory = Get-Location
$bytes = New-Object byte[] 4096
$in_file = [System.IO.File]::OpenRead($input_file)
$file_count = 0
$finished = $false
while (!$finished) {
$file_count++
$bytes_to_read = $split_size
$out_file = New-Object System.IO.FileStream ".\_split\_split_$file_count.splt",CreateNew,Write,None
while ($bytes_to_read) {
$bytes_read = $in_file.Read($bytes, 0, [Math]::Min($bytes.Length, $bytes_to_read))
if (!$bytes_read) {
$finished = $true
break
}
$bytes_to_read -= $bytes_read
$out_file.Write($bytes, 0, $bytes_read)
}
$out_file.Dispose()
}
$in_file.Dispose()
}
$i++
while (Test-Path ".\_split\_split_$i.splt") {
$cur_file = (Get-Content ".\_split\_split_$i.splt")
$temp_count = ([regex]::Matches($cur_file, "$pattern")).Count
$match_count += $temp_count
$n = $i - 1
if (Test-Path ".\_split\_split_$n.splt") {
if ($cur_file.Length -ge $pattern.Length) {
$file_transition = $prev_file.Substring($prev_file.Length - ($pattern.Length - 1)) + $cur_file.Substring(0,($pattern.Length - 1))
} else {
$file_transition = $prev_file.Substring($prev_file.Length - ($pattern.Length - 1)) + $cur_file
}
$temp_count = ([regex]::Matches($file_transition, "$pattern")).Count
$match_count += $temp_count
}
$prev_file = $cur_file
$i++
}
} else {
$a
$match_count = ([regex]::Matches($input_file, "$pattern")).Count
}
if ($delete -eq "true") {
Remove-Item ".\_split" -Force -Recurse
}
if ($match_count -ge 1) {
Write-Host "`n`n String '$pattern' found:`n`n $match_count matches!"
} else {
Write-Host "`n`n String '$pattern' not found!"
}
Write-Host `n`n`n`n`n
Pause
This will split a large file into mutliple smaller files, search them for $pattern and count the matches (taking file transitions into account).
It also offers you to delete or keep the splitted files afterwards so you can reuse them and don't have to split the large file every time you run this script.
Filenames on computer is named like so
quant-ph9501001
math9901001
cond-mat0001001
hep-lat0308001
gr-qc0703001
but on http links filenames is / character included
quant-ph/9501001
math/9901001
cond-mat/0001001
hep-lat/0308001
gr-qc/0703001
I can't rename my files quant-ph9501001 into quant-ph/9501001 because / is an illegal character so I can't use my code correctly to parse and rename from syntax to script actions.
Syntax of my filenames following this pattern:
letters + 8 digits
letters + '-' + letters + 8 digits
I can change quant-ph9501001 to quant-ph_9501001, but I need to parse missing character in filenames as if reading / (slash character).
So if I have strings like
gr-qc0701001
gr-qc_0701001
it should read like
quant-ph/9501001
My script don't working (no parsing) for gr-qc/0701001 because I can't rename filenames using illegal character. Error is 404.
iwr : The remote server returned an error: (404) Not Found.
If script works correctly PowerShell should be returns this string:
General Relativity and Quantum Cosmology (gr-qc)
and filename should be
Spectral Broadening of Radiation from Relativistic Collapsing Objects
My script is
$list1 = #"
quant-ph9802001
quant-ph9802004
"#
$list2 = #"
quant-ph/9802001
quant-ph/9802004
"#
Write-Output "Adding forward slashes"
$list1 -split "`r`n" | % {
$item = $_.Trim()
$newItem = $item -replace '(.*)(\d{7})', '$1/$2'
Write-Output $("{0} ==> {1}" -f $item, $newItem)
}
Write-Output "Removing forward slashes"
$list2 -split "`r`n" | % {
$item = $_.Trim()
$newItem = $item -replace '(.*)/(\d{7})', '$1$2'
Write-Output $("{0} ==> {1}" -f $item, $newItem)
}
Function Clean-InvalidFileNameChars {
param(
[Parameter(Mandatory=$true,
Position=0,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[String]$Name
)
$invalidChars = [IO.Path]::GetInvalidFileNameChars() -join ''
$re = "[{0}]" -f [RegEx]::Escape($invalidChars)
$res=($Name -replace $re)
return $res.Substring(0, [math]::Min(260, $res.Length))
}
Function Clean-InvalidPathChars {
param(
[Parameter(Mandatory=$true,
Position=0,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[String]$Name
)
$invalidChars = [IO.Path]::GetInvalidPathChars() -join ''
$re = "[{0}]" -f [RegEx]::Escape($invalidChars)
$res=($Name -replace $re)
return $res.Substring(0, [math]::Min(248, $res.Length))
}
$rootpath="c:\temp2"
$rootpathresult="c:\tempresult"
$template=#'
[3] arXiv:1611.00057 [pdf, ps, other]
Title: {title*:Holomorphy of adjoint $L$ functions for quasisplit A2}
Authors: Joseph Hundley
Comments: 18 pages
Subjects: {subject:Number Theory (math.NT)}
[4] arXiv:1611.00066 [pdf, other]
Title: {title*:Many Haken Heegaard splittings}
Authors: Alessandro Sisto
Comments: 12 pages, 3 figures
Subjects: {subject:Geometric Topology (math.GT)}
[5] arXiv:1611.00067 [pdf, ps, other]
Title: {title*:Subsumed homoclinic connections and infinitely many coexisting attractors in piecewise-linear maps}
Authors: David J.W. Simpson, Christopher P. Tuffley
Subjects: {subject:Dynamical Systems (math.DS)}
[21] arXiv:1611.00114 [pdf, ps, other]
Title: {title*:Faces of highest weight modules and the universal Weyl polyhedron}
Authors: Gurbir Dhillon, Apoorva Khare
Comments: We recall preliminaries and results from the companion paper arXiv:1606.09640
Subjects: {subject:Representation Theory (math.RT)}; Combinatorics (math.CO); Metric Geometry (math.MG)
'#
#extract utils data and clean
$listbook=gci $rootpath -File -filter *.pdf | foreach { New-Object psobject -Property #{file=$_.fullname; books= ((iwr "https://arxiv.org/abs/$($_.BaseName)").ParsedHtml.body.outerText | ConvertFrom-String -TemplateContent $template)}} | select file -ExpandProperty books | select file, #{N="Subject";E={Clean-InvalidPathChars $_.subject}}, #{N="Title";E={Clean-InvalidFileNameChars $_.title}}
#build dirs and copy+rename file
$listbook | %{$newpath="$rootpathresult\$($_.subject)"; New-Item -ItemType Directory -Path "$newpath" -Force; Copy-Item $_.file "$newpath\$($_.title).pdf" -Force}
EDIT: Error is still 404 this after Kori Gill answers
http://i.imgur.com/ZOZyMad.png
Problem is the difference between from local filenames and online filenames. I should add in memory temporally this illegal character in local filenames otherwise script doesn't work.
I can't say I totally understand your questions, but sounds like you just need to convert these names to/from a format that has or does not have a forward slash. You mention 8 digits, but your examples have 7. You can adjust as needed.
I think something like this will help you...
$list1 = #"
quant-ph9501001
math9901001
cond-mat0001001
hep-lat0308001
gr-qc0703001
"#
$list2 = #"
quant-ph/9501001
math/9901001
cond-mat/0001001
hep-lat/0308001
gr-qc/0703001
"#
Write-Output "Adding forward slashes"
$list1 -split "`r`n" | % {
$item = $_.Trim()
$newItem = $item -replace '(.*)(\d{7})', '$1/$2'
Write-Output $("{0} ==> {1}" -f $item, $newItem)
}
Write-Output "Removing forward slashes"
$list2 -split "`r`n" | % {
$item = $_.Trim()
$newItem = $item -replace '(.*)/(\d{7})', '$1$2'
Write-Output $("{0} ==> {1}" -f $item, $newItem)
}
Outputs:
Adding forward slashes
quant-ph9501001 ==> quant-ph/9501001
math9901001 ==> math/9901001
cond-mat0001001 ==> cond-mat/0001001
hep-lat0308001 ==> hep-lat/0308001
gr-qc0703001 ==> gr-qc/0703001
Removing forward slashes
quant-ph/9501001 ==> quant-ph9501001
math/9901001 ==> math9901001
cond-mat/0001001 ==> cond-mat0001001
hep-lat/0308001 ==> hep-lat0308001
gr-qc/0703001 ==> gr-qc0703001
The following Powershell script was wrote to scan and fix unquoted service paths containing white space within the referenced path susceptible to exploitation. The script, when ran ".\Get-ServicePathVulnerabilities" with any of the permitted switches, never executes the if statement for the $Fix (-Fix) switch. Please, review this source code and help me identify the issue, as this is a very convenient script to have in anyone's arsenal.
Function Get-ServicePathVulnerabilities {
[Cmdletbinding()]
Param (
[switch]$Fix
) # End Param
Begin {
$VulnerableServices=#()
if ($Fix){Write-Verbose "Scan Mode: Fix"} else {Write-Verbose "Scan Mode: Audit"}
} # End Begin
Process {
# Gather Services information from WMI
$Services = Get-WmiObject -Class win32_service -Property name,pathname
# Filter out services that have been enclosed with quotations
$UnquotedPath = $Services | Where-Object {$_.PathName -notmatch '"'} | Select Name,PathName
# Loop through services without quotations
foreach ($Path in $UnquotedPath) {
$Drive = $Path.PathName | Split-Path -Qualifier
$Executable = $Path.PathName | Split-Path -Leaf
# Conditional Logic to determine vulnerability
# Note: Some service paths may be unquoted and include spaces, but not vulnerable. They could just be a path to executable (no spaces) with a command line switch parameter that may contain a space.
# To avoid false positives, the logic below will exclude spaces used in any parameters
if( ($Path.PathName -match ' ') -and ($Executable -notmatch ' ') -and ($Path.PathName -notmatch './') ) {
# Vulnerability Found
Write-Warning ("Unquoted Service Path Discovered for " + $Path.Name + " PATH: " + $Path.PathName)
$VulnerableServices += New-Object PSObject -Property #{
ServiceName = $Path.Name
ServicePath = $Path.PathName
HostName = $env:COMPUTERNAME
} # End Object
} # End conditional operators
} # End Foreach Path in UnquotedPath
# Attempt to encapsulate path in quotes if specified
if ($Fix) {
$VulnerableServices | ForEach-Object {
Write-Verbose ("Attempting to fix " + $_.Servicename)
$OriginalPath = $_.ServicePath
$QuotedServicePath = ('"' + $_.ServicePath + '"')
$RegistryLocation = ('HKLM:\SYSTEM\CurrentControlSet\Services\' + $_.ServiceName)
Try {
Set-ItemProperty -Path $RegistryLocation -Name ImagePath -Value $QuotedServicePath -Verbose
$_.ServicePath = $QuotedServicePath
} Catch {
Write-Error ("Unable to fix " + $_.Servicename)
} # End Try/Catch
} # End Foreach object in VulnerableServices
} # End if Fix was Specified
} # End Process
End {
if ($VulnerableServices) {Return $VulnerableServices} else {Write-Verbose "No Unquoted Service path Vulnerabilites have been found"}
} # End End
} # Get-ServicePathVulnerabilites
I've been trying to execute the following code to pull information out of an Excel spreadsheet but it keeps failing with the following error:
Method invocation failed because [System.__ComObject#{000208d8-0000-0000-c000-000000000046}] doesn't contain a method named 'cells'.
At run.ps1:42 char:52
+ for ($row = [int]$matches[1] + 1; $sh.cells <<<< ($row, 2) -ne ""; $row++)
+ CategoryInfo : InvalidOperation: (cells:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Any idea how I can resolve this? Here is my code:
$(for ($i=3; $i -le $wb.sheets.count; $i++){
$sh=$wb.Sheets.Item($i)
$startCell_appname = $sh.cells.item(1,2).EntireColumn.find("Application Name").Address()
if ($startCell_appname -match '\$\w+\$(\d+)')
{
for ($row = [int]$matches[1] + 1; $sh.Cells($row, 2) -ne ""; $row++)
{
$apps = "" | Select appname,location,lob,os
$apps.appname = $sh.Cells($row, 2).Value2
# I don't know if the location value is in column 3; this is just an example.
$apps.location = $sh.Cells($row, 3).Value2
$apps.lob = $sh.Name
$apps.os = "Windows 7"
$apps
}
}
}) | Export-csv "apps.csv" -NoTypeInformation
Use $sh.Cells.Item($row,2) like you do where you are assigning to $startCell_appname.