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.
Related
So i'm trying to run CleanMgr via powershell on a remote computer. Since CleanMgr has a GUI Powershell cannot run it directly, as described here
If you do this then CleanMgr will hang forever waiting for user input. So this means we have to approach this differently.
I tried several approaches, see below. But non of them works like i would. It still hangs OR runs attached from powershell giving no feedback when done.
Simply put i want to run (remotely) CleanMgr on our Office PC's from my PC (Domain Admin).
Invoke-Command -ComputerName $ComputerOBJ -ScriptBlock {
# Create registry values
Write-Host "Setup keys..."
$volumeCaches = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
foreach ($key in $volumeCaches) {
Set-ItemProperty -Path "$($key.PSPath)" -Name StateFlags0333 -Value 2
}
# Execute Disk Cleanup Tool (cleanmgr.exe)
#Write-Host 'Starting CleanMgr.exe...'
Attempt 1:
Start-Process -FilePath "CleanMgr.exe" -ArgumentList '/sagerun:333' -NoNewWindow
Attempt 2:
Start-Process -FilePath "CleanMgr.exe" -ArgumentList '/sagerun:333' -WindowStyle Hidden
Attempt 3:
Invoke-WmiMethod -Class Win32_Process -Name "Create" -ArgumentList 'CleanMgr.exe /sagerun:333'
Attempt 4:
C:\temp\PsExec.exe \\$ComputerOBJ CleanMgr.exe /sagerun:333
Attempt 5:
$A = New-ScheduledTaskAction -Execute "cleanmgr.exe" -Argument '/sagerun:333'
$T = New-ScheduledTaskTrigger -Once -At (get-date).AddSeconds(1); $t.EndBoundary = (get-date).AddSeconds(60).ToString('s')
$S = New-ScheduledTaskSettingsSet -StartWhenAvailable -DeleteExpiredTaskAfter 00:00:30
Register-ScheduledTask -Force -user SYSTEM -TaskName "Run CleanMgr" -Action $A -Trigger $T -Settings $S
#Wait until Clean is done.
Write-Host 'Waiting for CleanMgr and DismHost processes to complete...'
Get-Process -Name cleanmgr, dismhost -ErrorAction SilentlyContinue | Wait-Process
# Remove the previously created registry values
Write-Host "Cleanmgr completed, now deleting keys"
$volumeCaches = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
foreach ($key in $volumeCaches) {
Remove-ItemProperty -Path "$($key.PSPath)" -Name StateFlags0333 -Force
}
}
I am trying to upgrade Powershell on a bunch of Windows 7 boxes so I can do other remote installs and such. I am using Invoke-Expression but I swear this worked once before without it. There doesn't appear to be a Wait option for any of this. It does work when I run the Invoke-Expression locally. I also tried Start-Process. Is there a better way to get feedback on why it didn't run? The debugging is painfully slow because it has been a lot of just guessing, both due to lack of feedback and due to its hard to tell on the remote machine when its actually installing the background. The script is getting copied. I've tried without the Remove-item in case I was deleting it too fast. The $cred is admin. I'm not sure Execution Policy is necessary.
foreach ($comp in $computers) {
$comp.Name
if(test-connection -ComputerName $comp.Name -quiet ){
$Destination = "\\$($comp.Name)\c$\Temp\"
copy-item -path "\\10.1.32.161\New Client Setups\WMF_5.1_PowerShell\*" -Destination $Destination -recurse -force
"`t Copied"
$session = Enter-PSSession $comp.Name -Credential $cred
$results = Invoke-Command -ComputerName $comp.Name -ScriptBlock {
Set-ExecutionPolicy RemoteSigned
$ver = $PSVersionTable.PSVersion.Major
"`t Powershell Version : $ver"
if ($ver -lt "5"){
"`tNeeds upgrade"
$argumentList = #()
$argumentList += , "-AcceptEULA"
$argumentList += , "-AllowRestart"
#Invoke-Expression "& 'C:\Temp\Windows7_Server2008r2\Install-WMF5.1.ps1' + $argumentList"
Invoke-Expression 'C:\Temp\Windows7_Server2008r2\Install-WMF5.1.ps1 -AllowRestart -AcceptEULA'
}
}
$results
Remove-item -Path "$Destination*" -recurse
Exit-PSSession
Remove-PSSession -session $session
I'm trying to run a powershell script from rundeck(linux), If I run the script locally[Deletes some files from multiple terminal servers](Windows server) it is working as expected however if I call it from rundeck server(winrm configured) it seems that the script cant access the remote folders I'm trying to access.
I tried running the script using the same user but still shows different result.
Script bellow:
$userAD = "someuser"
$servers = Get-Content C:\TSList.csv
$Folder = "c$\Users\$userAD\"
$TSFolderShare = "\\sharepath"
Write-Output "#####Start of script#####"
Write-output `n
Write-output "Checking if $userAD user profile exist in Terminal servers..."
sleep -seconds 1
foreach ($server in $servers) {
Test-Path "\\$server\$Folder" -PathType Any
Get-ChildItem "\\$server\$Folder"
if (Test-Path "\\$server\$Folder" -PathType Any) {
Write-output "Resetting user profile in $server.."
Get-ChildItem "\\$server\$Folder" -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
sleep -seconds 1
Write-output "Done."
if( (Get-ChildItem "\\$server\$Folder" | Measure-Object).Count -eq 0)
{
Write-output "Done."
}
}
else
{
Write-output "Resetting user profile in $server.."
sleep -seconds 1
Write-output "User profile does not exist in $server."
#Write-output "\\$server\$Folder does not exist in $server!" -ForegroundColor Red
}
}
EDIT: It seems my problem is when running my script from another script with RunAS.
Below I'm trying to access a folder from another server using ps script, but since I want to integrate this to Rundeck I need to call my ps script from my linux server using python. I did a test running the ps script directly and calling the test path script using another script with RunUs using the same user I used to run the script manually
Scenario 1
Running PS script via separate PS script with RunAS(my_account)
$username = "my_account"
$password = "my_password"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
Invoke-Command -FilePath "C:\testpath.ps1" -Credential $cred -Computer localhost
(C:\testpath.ps1) Content below:
Test-Path "\\server\c$\Users\myaccount\"
result:
Access is denied
+ CategoryInfo : PermissionDenied: (\server\c$\Users\myaccount:String) [Test-Path], UnauthorizedAccessException
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.TestPathCommand
+ PSComputerName : localhost
False
Scenario 2
Running C:\testpath.ps1 directly as my_account
Test-Path "\\server\c$\Users\myaccount\"
result:
True
I used session configuration in powershell to solve the issue. This way allows you to tie a credential to a PowerShell session configuration and reuse this configuration for all future connections.
https://4sysops.com/archives/solve-the-powershell-multi-hop-problem-without-using-credssp/
Thanks a lot!
You're facing a double-hop issue with Rundeck and Powershell, here the explanation. That's asked before, take a look a this, and here a good workaround. Also this to solve it.
What i'm trying to do ?
Create four files in local disk in the following order.
Note : In my local machine and not in any server remotely.
Three files to be created
Restart the system
On system startup create another file
Script i have used.
get-job | remove-job -Force
function create-file {
Param ([string] $a)
$p = "D:\" + $a
Write-Host $p
if (!(Test-Path $p))
{
New-Item -path D:\$a -type "file" -value "my new text"
Write-Host "Created new file and text content added"
}
else
{
Add-Content -path D:\$a -value "new text content"
Write-Host "File already exists and new text content added"
}
}
Workflow New-ServerSetup
{
create-file "one.txt"
create-file "two.txt"
create-file "three.txt"
Restart-Computer -ComputerName $env:COMPUTERNAME -Wait
Start-Sleep -Seconds 7
create-file "four.txt"
Unregister-ScheduledJob -Name NewServerSetupResume
}
$adm = "####"
$pwd = ConvertTo-SecureString -String "####" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($adm, $pwd)
$AtStartup = New-JobTrigger -AtStartup
Register-ScheduledJob -Name NewServerSetupResume -Credential $cred -Trigger $AtStartup -ScriptBlock {Import-Module PSWorkflow; Get-Job -Name NewSrvSetup -State Suspended | Resume-Job}
New-ServerSetup -JobName NewSrvSetup
Issues i'm facing
The execution returns Cannot wait for local computer to restart
i'm new to powershell things if any mistakes burden me.
Thanks in advance.
Schedule a job first, then reboot without waiting.
Change a value in a winlogbeat.yml as it is passed to serveral remote servers. Here is the value to change > hosts: localhost:5044 and when script kicks off on remote server it is to change to >lp-index-QA.QA.com:9999
Here is the script I wrote.. no failures but does not pass the new value to remote server>>
#ExecutionPolicy
Set-ExecutionPolicy -Force Unrestricted
#DC = (facter datacenter) | Out-String
$DC = 'parpr1'
$QAhost = #("hosts: lp-index-QA.QA.com:9999", "`r`nhosts: localhost:5044")
$PRODhost = #("hosts: lp-index-PROD.PROD.com:9999", "`r`nhosts: localhost:5044")
$file = 'C:\winlogbeat-1.2.3-windows\winlogbeat.yml'
if ($DC -eq "QA")
{
Write-Host "Datacenter is $DC"
Add-Content -PassThru -Path "$file" -Value "hosts: lp-index-QA.QA.com:9999"
}
if ($DC -eq "PROD")
{
Write-Host "Datacenter is $DC"
Add-Content -PassThru -Path "$file" -Value "hosts: lp-index- PROD.PROD.com:9999"
}
# delete service if it already exists
if (Get-Service winlogbeat -ErrorAction SilentlyContinue) {
$service = Get-WmiObject -Class Win32_Service -Filter "name='winlogbeat'"
$service.StopService()
Start-Sleep -s 1
$service.delete()
}
$workdir = Split-Path $MyInvocation.MyCommand.Path
# create new service
New-Service -name winlogbeat `
-displayName winlogbeat `
-binaryPathName "`"$workdir\\winlogbeat.exe`" -c `"$workdir\\winlogbeat.yml`""
#pause 5s
Start-Sleep -s 10
#Startingserver
Start-service winlogbeat