How to set variable path in Azure Functions with PowerShell - powershell

Here is my PowerShell script that takes back up of Postgresql server in remote location.
Also postgres is installed in my local PC.
Set-Location 'C:\Program Files\PostgreSQL\12\bin\';
$env:PGPASSWORD = 'MyPassword';
$bkpBaseFolder = 'D:\dbBackup\';
$PGPATH="C:\Program Files\PostgreSQL\12\bin\pg_dump.exe";
$cdate = (Get-Date).ToString('dd-MMM-yy_HH-mm');
$NewFolder = $bkpBaseFolder + $cdate + '\';
New-Item -ItemType Directory -Force -Path $NewFolder;
$dbs = .\psql -h mysite.com -U postgres -c 'SELECT datname FROM pg_database WHERE datistemplate = false;'
foreach($db in $DBs) {
$fileName = $NewFolder + $db + '.bkp';
& $PGPATH -h mysite.com -U postgres -f $fileName -d $db
}
I want to move this script to Azure Functions with Powershell to run on specified time everyday.
How do I set Path variables of pg_dump or other local paths without installing it?

Related

How to execute pg_dump in PowerShell and redirect the output to a file

My goal is to have a ps1-script which consider different local postgreSQL instances to dump and restore several databases. The expected result is a folder with the dumped data and a logfile of the actions done, due to have control if everything went ok.
My hurdels:
either I get no output of the actions done (script Run-01-*)
the execution of the script hangs (script Run-02-*)
pg_dump can't connect to the database (script Run-03-*)
Here are my results:
<#
Run-01-pg_dump-POSTGRES-Powershell-excutes-OK.ps1
NOTE: replace 'mypassword' and 'mydatabase' to your local settings
dump the database 'mydatabase' to folder 'D:\Temp\01-DATABASE.Dump.OK'
=> works fine, BUT makes no output to have control whether everythings went correct
=> REASON: pg_dump.exe writes its actions to StandardError
#>
$process = [System.Diagnostics.Process]::Start([System.Diagnostics.ProcessStartInfo]#{
FileName = 'C:\Program Files\PostgreSQL\12\bin\pg_dump.exe'
Arguments = #('-d', 'postgresql://postgres:mypassword#localhost:5432/mydatabase', '--no-owner', '--no-privileges', '-C','-c', '-b', '-EUTF-8', '-v', '-Fd', '-Z9', '-f', 'D:\Temp\01-DATABASE.Dump.OK')
CreateNoWindow = $true
UseShellExecute = $false
RedirectStandardInput = $false
RedirectStandardOutput = $true
RedirectStandardError = $false
})
$output = $process.StandardOutput
$out = $output.ReadToEnd() # reads from stdout
$out
Now I tryed to capture StandardError.
<#
Run-02-pg_dump-POSTGRES-Powershell-HANGS.ps1
NOTE: replace 'mypassword' and 'mydatabase' to your local settings
dump the database 'mydatabase' to folder 'D:\Temp\02-DATABASE.Dump.HANGS'
=> The execution of the script hangs. Nothing is written to the folder (is empty), no output of 'pg_dump'
=> the process has to be terminated by the windows "task managaer'
=> after termination, the pg_dump writes partly actions to the standardError
#>
$process = [System.Diagnostics.Process]::Start([System.Diagnostics.ProcessStartInfo]#{
FileName = 'C:\Program Files\PostgreSQL\12\bin\pg_dump.exe'
Arguments = #('-d', 'postgresql://postgres:mypassword#localhost:5432/mydatabase', '--no-owner', '--no-privileges', '-C','-c', '-b', '-EUTF-8', '-v', '-Fd', '-Z9', '-f', 'D:\Temp\02-DATABASE.Dump.HANGS')
CreateNoWindow = $true
UseShellExecute = $false
RedirectStandardInput = $false
RedirectStandardOutput = $true
RedirectStandardError = $true
})
$output = $process.StandardOutput
$stderror = $process.StandardError
$out = $output.ReadToEnd() # reads from stdout
$out
$err = $stderror.ReadToEnd() # reads from stderr
$err
Then I stumpled over the hint to do it with the commandlet 'Start-Process'.
<#
Run-03-pg_dump-POSTGRES-Powershell-using-commandlet-Start-Process-CONNECTION-FAILS.ps1
NOTE: replace 'mypassword' and 'mydatabase' to your local settings
dump the database 'mydatabase' to folder 'D:\Temp\03-DATABASE.Dump.CONNECT-FAILS'
=> The execution of the script failes.
=> 03-pd_dump-error:
log pg_dump: Fehler: Verbindung zur Datenbank »mydatabase« fehlgeschlagen: konnte Hostnamen »localhost« nicht in Adresse übersetzen: Unknown server error
#>
$processArguments = #('-d', 'postgresql://postgres:mypassword#localhost:5432/mydatabase', '--no-owner', '--no-privileges', '-C','-c', '-b', '-EUTF-8', '-v', '-Fd', '-Z9', '-f', 'D:\Temp\03-DATABASE.Dump.CONNECT-FAILS')
$processOptions = #{
FilePath = 'C:\Program Files\PostgreSQL\12\bin\pg_dump.exe'
ArgumentList = #($processArguments)
RedirectStandardOutput = "d:\Temp\03-pd_dump-output.log"
RedirectStandardError = "d:\Temp\03-pd_dump-error.log"
NoNewWindow = $false
UseNewEnvironment = $true
}
Start-Process #processOptions -wait
This lead to another error (refer 03-pd_dump-error' in script header) which i can't understand, because the postgres URI for connection worked properly in 01 and 02, even in the following 04.
REM
REM Run-04-pg_dump-POSTGRES-commandline-OK.cmd
REM
REM NOTE: replace 'mypassword' and 'mydatabase' to your local settings
REM dump the database 'mydatabase' to folder 'D:\Temp\04-DATABASE.Dump.OK'
REM
REM => works fine
"C:\Program Files\PostgreSQL\12\bin\pg_dump.exe" -d postgresql://postgres:mypasswordmypassword#localhost:5432/mydatabase --no-owner --no-privileges -C -c -b -EUTF-8 -v -Fd -Z9 -f D:\Temp\04-DATABASE.Dump.OK 2>>D:\Temp\04-pd_dump-error.log
I am using postgreSQL version 12 and 13 with the related pg_dump, pg_restore.
Any help, advice, hint to solve the problem would be highly appreciated.

PSExec registry file remotly

I am trying to execute a PowerShell to execute a reg file remotly
This is what I have at the moment:
$computer = 'IP';
$username = 'user';
$password = 'password';
$reg = 'regedit /s //ip/teste.reg';
$reg_command = "psExec -i -d -c -f -s \\$computer -u $computer\$username -p $password `"$reg`"";
Write-Output "Inserting regestry file...";
Invoke-Expression $reg_command;
I have psExec in my computer, but I don't know how I would add the path executable for PSExec in the code.

Retrieve password from Import-Clixml to login sqlplus using Powershell Get-credential

I have a powershell script that will automatically run the SQL query in the SQLPlus hourly through the task scheduler.
The below code run successfully.
$username = "abcuser";
$password = "123pw";
$dir = "D:\SQL\Test"
cd $dir
echo exit | sqlplus $username/$password '#Justscript.sql
But I want to store the credentials through Get-Credential for security, thus did it this way. Note that I have already ran the Get-credential and exported the credentials
$db_filename = 'C:\Users\Maria Maria\db_credentials.txt'
$db_cred = Import-Clixml -Path $db_filename
$dir = "D:\SQL\Test"
cd $dir
#this doesn't work
echo exit | sqlplus $db_cred '#Justscript.sql
this doesn't work either
$username = $db_cred.UserName;
$password = $db_cred.Password;
echo exit | sqlplus $username/$password '#Justscript.sql
This was able to read the username, but the password don't. Do you have other way?
This is how you get the plaintext data from Get-Credential:
$credentials = Get-Credential
$username = $credentials.UserName
$password = $credentials.GetNetworkCredential().password

Powershell pass parameter to sqlcmd

I'm trying to pass username, db and pwd as variable to sqlcmd - but it does not seem to like it.
This works
#Run SQLCMD for each file
ForEach ($FileName in $FileNames)
{
Write-Host $FileName.BaseName
sqlcmd -S 123.database.net -d EMR -U user1-P mypassword -i $FileName.FullName
}
This does not work
#Run SQLCMD for each file
$db = "123.database.net"
$dbId = "user1"
$pwd = "mypassword"
ForEach ($FileName in $FileNames)
{
Write-Host $FileName.BaseName
sqlcmd -S $db -d EMR -U $dbId -P $pwd -i $FileName.FullName
}
Error message
sqlcmd : Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : Login failed for user 'user1'..
sqlcmd has its scope .Make the variables as Global. Then it should pick it.
DO this:
#Run SQLCMD for each file
$global:db = "123.database.net"
$global:dbId = "user1"
$global:pwd = "mypassword"
ForEach ($FileName in $FileNames)
{
Write-Host $FileName.BaseName
sqlcmd -S $db -d EMR -U $dbId -P $pwd -i $FileName.FullName
}
Note: I have not taken into consideration that your second scriptlet is throwing any error in particular or not.

how to "sudo root" with posh-ssh (powershell)

i am using posh-ssh to connect to my ssh server do some commands start with su root,but i can not switch user to root sucessfully.
PS C:\> $rootpwdSec = ConvertTo-SecureString $rootpwd -AsPlainText -Force
PS C:\> Invoke-SSHStreamExpectSecureAction -Command 'su ' -ExpectString 'Password:' -SecureAction $rootpwdSec -ShellStream $stream
True
PS C:\> $stream.read();
[root#aaaaaa-test admin]#
PS C:\> Invoke-SSHCommandStream -SessionId $SessionId -Command 'id'
uid=500(admin) gid=500(admin) groups=500(admin) context=user_u:system_r:unconfined_t
PS C:\>
how can run my command as root?
What I noticed when working with posh-ssh and ubuntu was I was failing to sudo up to root using "sudo su -" due to the ExpectString. It was expecting "[sudo] password for (username):" and I was merely providing "password:"
$stream = $session.Session.CreateShellStream("PS-SSH", 0, 0, 0, 0, 100)
$user = Invoke-SSHCommand $session -Command "whoami"
$SSHusersName = $user.Output | Out-String
$SSHusersName = $SSHusersName.Trim()
$results = Invoke-SSHStreamExpectSecureAction -ShellStream $stream -Command "sudo su -" -ExpectString "[sudo] password for $($SSHusersName):" -SecureAction $secpas
$stream.Read()
This was how I was able to sudo to root. Again it may be different for you depending on what *nix variant you are connecting to.