Script running on windows 10 but not on windows 7 - windows

I have written a script that works great on my machine (Windows 10) but I see an error when I run this code on other machine (Windows 7).
I need the script to check in c:\users\username\ directory for existence of tor.exe or directory called tor. The code for this part is this:
function FindTor() {
[int]$answer=0
$path = "C:\users\$env:username\"
$torEXE = Get-ChildItem -path $path -recurse -erroraction 'silentlycontinue' | Where-Object name -eq "Tor.exe"
$torDIR = Get-ChildItem -path $path -recurse -erroraction 'silentlycontinue' | Where-Object name -eq "tor"
if ($torEXE.Exists -or $torDIR.Exists) {$answer = 1}
Return $answer
}
On my computer - no problem. On the machine with windows 7 I get this:

Related

HOWTO Discover Postgres Running in Windows Environment

HOWTO Discover Postgres Running in Windows Environment
So How do we discover all the Postgres installed in our Windows 2012R2/2016 environment with PowerShell?
I wrote this script but I am told that will not find ALL postgres instances, if the install was not coded to create a service... Ideas?
#List-PostGres-Servers.ps1
Remove-Item -force "drive\path\*-List-PostGres-Servers-log.txt" -ErrorAction
ignore
$today = (Get-Date -Format yyyyMMdd)+"-"+(get-date -uformat %H)
Start-Transcript -Path "drive\path\$today-List-PostGres-Servers-log.txt"
$servers = get-content 'drive\path\input\listofservers.txt'
foreach ($server in $servers){
if ((Test-Connection -Count 1 -ComputerName $server -quiet) -eq $false){continue}
else{
$PostGresSearch = (get-service -ComputerName $server -name *postgres* -ErrorAction Ignore -WarningAction Ignore -InformationAction Continue)
$PostGresServicename = $PostGresSearch.Name
#|out-file -Encoding ascii "drive\path\output\DOMAINNAME-CheckListPostgres.txt" -force -Append
if ($PostGresServicename -eq $null){continue}
else {
$server+","+" "+$PostGresServicename
}
}
}
You could check to see if postgres is currently running with:
Get-Process *postgres*
In the case where neither a service is installed nor is the binary running, then you're not using that postgres install. Alternatively, search $env:ProgramFiles or ${env:ProgramFiles(x86)} for psql.

How can I use a variable filled with a path to navigate or execute in PowerShell?

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;
}
Although I'm not sure what your desired output should look like, but below creates an array of PSObjects that you can output on screen or write to CSV file.
$result = Get-ChildItem -Path C:\ -Filter java.exe -File -Recurse -ErrorAction SilentlyContinue -Force | ForEach-Object {
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $_.FullName
$pinfo.Arguments = "-version"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $pinfo
$process.Start() | Out-Null
$process.WaitForExit()
$output = $process.StandardOutput.ReadToEnd()
if (!$output) { $output = $process.StandardError.ReadToEnd() }
[PsCustomObject]#{
'FileName' = $_.FullName
'VersionInfo' = $output
}
}
# output on screen
$result | Format-List
# output to CSV file (VersionInfo field uses multiple lines)
$result | Export-Csv -Path 'D:\javaversions.csv' -UseCulture -NoTypeInformation
Result on screen wil look something like:
FileName : C:\Program Files\Java\jdk1.8.0_31\bin\java.exe
VersionInfo : java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)
FileName : C:\Program Files\Java\jdk1.8.0_31\jre\bin\java.exe
VersionInfo : java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)
FileName : C:\Program Files\Java\jre1.8.0_221\bin\java.exe
VersionInfo : java version "1.8.0_221"
Java(TM) SE Runtime Environment (build 1.8.0_221-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.221-b11, mixed mode)
Your code doesn't work because you're writing entire commandlines to the intermediate file and then try to invoke the command strings from this file via the call operator. That doesn't work because a command "'C:\path\to\java.exe' -version" doesn't exist. You should be getting an error like this:
PS C:\> $command = "'C:\path\to\java.exe' -version"
PS C:\> & $command
& : The term ''C:\path\to\java.exe' -version' 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.
At line:1 char:3
+ & $command
+ ~~~~~~~~
+ CategoryInfo : ObjectNotFound: ('C:\path\to\java.exe' -version:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
The simplest way to make your code work is to just invoke the executables directly:
Get-ChildItem -Path 'C:\' -Filter 'java.exe' -Recurse -EA SilentlyContinue -Force |
ForEach-Object {
$_.FullName + ' -version'
& $_.FullName -version 2>&1
'__________________'
} |
Set-Content $out
If you want to stick with the approach using an intermediate file you need to prepend the commandline with the call operator, convert it to a scriptblock, and then invoke that.
Get-Content $file | ForEach-Object {
$command
& ([Scriptblock]::Create("& $command")) 2>&1
'__________________'
} | Out-File $out
An alternative solution to #Theo is using a temporary file like so:
$GetParams = #{
Path = 'C:\'
Filter = 'java.exe'
Recurse = $true
Force = $true
File = $true
ErrorAction = 'SilentlyContinue'
}
$JavaExeFiles = Get-ChildItem #GetParams | select -First 1
$StartParams = #{
ArgumentList = '-version'
NoNewWindow = $true
RedirectStandardError = '.\javaver.txt'
}
$JaveExeDetails = foreach ($JaveExe in $JavaExeFiles) {
Remove-Item -Path $StartParams.RedirectStandardError -EA Ignore
Start-Process #StartParams -FilePath $JaveExe.FullName -Wait
[PSCustomObject]#{
File = $JaveExe.FullName
Version = Get-Content -Path $StartParams.RedirectStandardError
}
}
# For viewing in the console
$JaveExeDetails | fl *
# For export to a file
$JaveExeDetails | fl * | Out-File -FilePath ./JavaVersions.txt

Copy and paste the latest modified log files from one server to other server (the servers are in the different domains)

I am trying to write a script that copies the latest modified log file from one server to another server (servers are in different domains), while copying it should check for the credentials and then execute the script.
Please let me know if the script is correct or any corrections to be made.
$sourcePath = 'sourcepath'
$destPath = 'Destinationpath'
$compareDate = (Get-Date).AddDays(-1);
$LastFileCaptured = Get-ChildItem -Path $sourcePath |
where {$_.Extension.EndsWith('.log') -and $_.LastWriteTime -gt $compareDate } |
Sort LastAccessTime -Descending |
select -First 1 |
select -ExcludeProperty Name, LastAccessTime
Write-Host $LastFileCaptured.Name
$LastFileCaptured.LastAccessTime
$LastFileCaptured = Get-ChildItem -Recurse |
Where-Object{$_.LastWriteTime.AddDays(-1) -gt (Get-Date)}
Write-Host $LastFileCaptured
Get-ChildItem $sourcePath -Recurse -Include '.log' | Where-Object {
$_.LastWriteTime.AddDays(-1).ToString("yyyy/MM/dd") -gt (get-date).ToString("yyyy/mm/dd")
} | ForEach-Object {
$destDir = Split-Path ($_.FullName -replace [regex]::Escape($sourcePath), $destPath)
if (!(Test-Path $destDir)) {
New-Item -ItemType directory $destDir | Out-Null
}
Copy-Item $_ -Destination $destDir
}
The "correctness" of your script is determined easily by running it! But, while this isn't a direct answer, I would suggest robocopy for this task.
In particular note these options:
/mon: Monitors the source, and runs again when more than N changes are detected.
/maxage: Specifies the maximum file age (to exclude files older than N days or date).

Search for registry key path

please, could you help me with searching for registry path?
I am trying to find path of REG_BINARY with name 00036601 in HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Outlook\Profiles\Outlook\20424cec73cea54ab3d011f91bf036b2
I have problem because last folder(20424cec73cea54ab3d011f91bf036b2) in path is different on every laptop. Cannot find any working solution with REG QUERY in cmd or powershell.
I know how to find it in known path or list all subkeys, but failed to filter one value.
So i want to get output like: key name 00036601 found in HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Outlook\Profiles\Outlook\20424cec73cea54ab3d011f91bf036b2
EDIT: sorry for my english, maybe i am notz describing it correctly, please, could you look on image?
Regedit
I am looking for string name 00036601 - marked in image. Thanks for help
EDIT2: i found way how to do it with cmd "REG QUERY HKCU\SOFTWARE\Microsoft /s /f 00036601"
But not with powershell...
You can search the registry with PowerShell. I do not have the same registry path as you have.
Get-ChildItem -Path HKCU:\Software\Microsoft\Office\16.0 `
-Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.PSChildName -eq '00036601' }
If you must do it from a cmd.exe shell:
powershell -NoLogo -NoProfile ^
"Get-ChildItem -Path HKCU: -Recurse -ErrorAction SilentlyContinue | " ^
"Where-Object { $_.PSChildName -eq '00036601' }"
EDIT: that was never going to get there.
This works on my machine to find the IM enabled setting.
$r = Get-ChildItem -Path 'HKCU:/Software/Microsoft/Office/' -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.Property -eq 'EnablePresence' }
(Get-ItemProperty -Path $r.PSPath).EnablePresence
Please try this on your machine.
$r = Get-ChildItem -Path 'HKCU:/Software/Microsoft/Office/' -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.Property -eq '00036601' }
(Get-ItemProperty -Path $r.PSPath).'00036601'

Expected Identifier Code Error when running script?

I got this script off the technet website, but I get an error when I try to execute it on my Windows 7 machine. I am completely new to scripting, but I wonder if this was made for an older OS and needs a bit of changing for Windows 7? I'm quite sure the guy who wrote it up tested it.
I get the Windows Script Host Error as follows:
Line: 1
Char: 10
Error: Expected Identifier
Code: 800A03F2
Source: Microsoft VBScript compilation error.
Here's the script:
Function New-BackUpFolder($destinationFolder)
{
$dte = get-date
$dte = $dte.tostring() -replace "[:\s/]", "."
$backUpPath = "$destinationFolder" + $dte
$null = New-Item -path $backUpPath -itemType directory
New-Backup $dataFolder $backUpPath $backUpInterval
} #end New-BackUpFolder
Function New-Backup($dataFolder,$backUpPath,$backUpInterval)
{
"backing up $dataFolder... check $backUppath for your files"
Get-Childitem -path $dataFolder -recurse |
Where-Object { $_.LastWriteTime -ge (get-date).addDays(-$backUpInterval) } |
Foreach-Object { copy-item -path $_.FullName -destination $backUpPath -force }
} #end New-BackUp
# *** entry point to script ***
$backUpInterval = 1
$dataFolder = "C:\fso"
$destinationFolder = "C:\BU\"
New-BackupFolder $destinationFolder
that's actually Powershell and not VB script. You need to run the code inside Powershell for this to work.
This link looks pretty good for a brief introduction if you haven't done PS before.
http://www.abstrys.com/files/BeginningPowershellScripting.html

Resources