I'm currently writing a PowerShell script for the first time. I just want to find out which Java versions I have running on my Windows machines. It is searching for all java.exe instants, writes it in a file and then it should execute each line and write the output in a file. But I can't use my variable $command to execute anything. So the for loop is just running one time, because of an error and then quits.
#declaration
$file = ".\text.txt"
$i = 3
$out = ".\output.txt"
Get-ChildItem -Path C:\ -Filter java.exe -Recurse -ErrorAction SilentlyContinue -Force |
Select-Object Directory >> $file
$count = Get-Content $file | Measure-Object -Line
#remove spaces and append "java.exe"
(Get-Content $file | Foreach {$_.TrimEnd()}) | Set-Content $file
(Get-Content $file | foreach {$_ + "\java.exe' -version"}) | Set-Content $file
(Get-Content $file).Replace("C:", "'C:") | Set-Content $file
#remove last 2 lines of the file
$count = $count.Lines - 2
#execute the stored paths
$i = 3
for ($i=3; $i -le $count; $i++) {
$command = Get-Content $file | Select -Index $i;
$command >> $out;
& $command 2> $out; # <----------------This line wont work
echo "_____________________" >> $out;
}
C:\paht\java.exe -versionon each installation you have to find the version of java installed?& exe argumenton a line not& somestring. If you are adding the single quotes to make this part of the code work, then that is not necessary. For yours to work as is, you would need to do something like this& ($command -split " (-version)" -replace "'")[0] ($command -split " (-version)" -replace "'")[1]. The reason is because the first set of double quotes after&is interpreted as the command rather than the command and arguments.