How do I zip a SQL Server backup file using Powershell and save in the same directory? - sql-server

I am trying to zip up a SQL Server backup file and save it in the same directory using PowerShell. The only way it works for me is if I move it to a temp folder then zip it up and move it back to the original folder. But I don't want to move it. I just want to keep it in the existing folder and ignore all other files in the folder. The zip file name should be the same name as the backup file with extension as .zip and it doesn't need to be in a folder.
Here is my code (which I would like to change)
#Backup SQL database
Backup-SqlDatabase -Database Mydbname -ServerInstance MyServerName- BackupSetName "Mydbname-Full Database Backup" -DatabaseFile Mydbname.bak -ExpirationDate 0 -Initialize
#Move backup to temp location and Zip the folder
$temppath = "C:\Temp\Bkup"
$sourcepath = "C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\Mydbname.bak"
$destpath = "C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\"
Move-Item -Path $sourcepath -Destination $temppath
Compress-Archive -Path $temppath -DestinationPath\Mydbname.bak.zip
Is there a way to streamline this code so that it doesn't create a new folder?
Note: If I run the script twice, it will fail the second time around because I still have the moved file in the temp folder. Is there a way to delete the file from the temp location after moving it back to the original folder. (I am new to PowerShell.)

Since your source is one file, try this. Compress archive can take a source as a single file. I commented out 2 of the lines.
$sourcepath = "C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\Mydbname.bak"
$destpath = "C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\"
Compress-Archive -Path $sourcepath -DestinationPath\Mydbname.bak.zip

Related

How to run the PowerShell batch file or a command.ps1 file through SQL server if sql is in one sever and file is in another server

I want to connect two VM/server one has data file and batch file another have sql install wanted to trigger command of server A which will hit server b files
Sql command--- in server A
EXEC master..xp_cmdshell 'cd.. && "C:\Program Files\Powershell\6\pwsh.exe" -File "C:\Users\sprasad\Desktop\script\command1.ps1"'
error are
1- import-module: The specified module 'C:\Program
Files\Derivation_19_01_rev0\Core.PowershellModule.TradeLoader.dll' was
not loaded because no valid module file was found in any module
directory.
because files are in server B
I am running sql scripts stored in files (sqlscript.sql) on ServerA against a SQL installation on ServerB using remote powershell. The Powershel module SQLPS is needed on serverA.
see link
steps:
enable remotepowershell on serverB
Enable-PSRemoting -force
in your SQL server, add the user that executes the script on serverA in the list of users with rights on the database.
use a script on severA like:
Import-Module -Name SQLPS -NoClobber -DisableNameChecking -Scope Local Invoke-Sqlcmd -ServerInstance serverA -InputFile sqlscript.sql
-Verbose
Invoke-Sqlcmd -ServerInstance 'serverB' -InputFile sqlscript.sql -Verbose

TFS Run batch script on a remote server with admin permission

I currently have Server A which is where my TFS and Build Agent is located. I then have Server B which is when my source code site. I am trying to set up a build definition and copies file from on location in server B to another and then build the solution.
However when I run this batch file as part of a build definition it is not creating folders where it need to be. I believe due to the agent not having correct permissions.
Is there a way to run the following batch script to run with Admin permission from a build definition.
You can try below workarounds:
Convert the batch script to PowerShell script, then copy the
PowerShell script to target machine and use the PowerShell on Target
Machines task to run the script. You can enter your admin user
and password using the task. Reference below screenshot.
Add a PowerShell task and run below script to call the cmd.exe to
run the batch script with an admin user account on target machine
(Copy the batch script to target machine first, in below sample I
copied the batch script to C:\Scripts\Test.bat):
Param(
[string]$computerName = "v-tinmo-12r2",
)
$Username = "Domain\user"
$Password = ConvertTo-SecureString "password-here" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($Username,$password)
Invoke-Command -ComputerName $computerName -Credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'C:\Scripts\Test.bat'"}

Copying XAP file to ClientBin on the deployment server not working

All I am trying to do here is that I have a set of files in a network share folder and I am trying to copy them to the deployment server through a PS script.
The .dll and .pdb files are getting copied as expected to the "bin" folder. But the .xap file is not copied to the "ClientBin" folder.
I also tried placing the .dll file into the same folder. That didn't work either. Deleting from the folder also not working.
Here is a snippet from PS script I am using for the deployment.
try
{
# Copy all of the files from the source location to the deployment directory
Write-Host "DeployService: Deploying new files for ""$serviceWebSiteName""..."
Copy-Item $sourceDirectory"\*.dll" $deploymentDirectory
Copy-Item $sourceDirectory"\*.exe" $deploymentDirectory
Copy-Item $sourceDirectory"\*.pdb" $deploymentDirectory
Copy-Item $sourceDirectory"\*.xap" $deploymentDirectory2
Write-Host "DeployService: Deploying new files for ""$serviceWebSiteName""...complete"
}
catch
{
Write-Host $_.Exception.ToString() -foregroundcolor red
}
Verified the permissions for the user. The users have same permission on both "bin" folder and the "ClientBin". Not sure how it works for bin and does not for clientbin.
Will greatly appreciate any help or input here
Thanks

Batch file to move files from one FTP folder to another folder in the same FTP?

Good morning all,
I have a task where i need to automate a process where we download files from an FTP site, the files are processed in SQL, and then the files on the FTP site are moved to another folder on that same FTP site.
The first two parts i have down but the part of moving the files on the FTP to another folder on the same FTP is tripping me up.
Can anyone please offer some advice?
This is what i currently have:
#Echo Off
Set _FTPServerName=SERVER HERE
Set _UserName=LOGIN HERE
Set _Password=PASSWORD HERE
Set _RemoteFolder=FILES FROM
Set _NewRemoteFolder=FILES TO
Set _Filename=*.*
Set _ScriptFile=ftp1
:: Create script
"%_ScriptFile%" Echo open %_FTPServerName%
"%_ScriptFile%" Echo %_UserName%
"%_ScriptFile%" Echo %_Password%
"%_ScriptFile%" Echo cd %_RemoteFolder%
"%_ScriptFile%" prompt
:: Run script
ftp -s:"%_ScriptFile%"
Del "%_ScriptFile%"
Please let me know if you have further questions!
There's rename command in Windows ftp.exe command-line client:
rename oldname newname
So in your specific batch file:
"%_ScriptFile%" echo rename file.txt %_NewRemoteFolder%/file.txt
Though seeing the _Filename=*.* in your question, it actually looks like you want to move all files. That's not possible with Windows ftp.exe, at least not easily. The rename command does not support wildcards.
You would have to dynamically generate a script file based on a list of downloaded files with a separate rename command for each file.
Or use a different command-line FTP client that supports wildcards when renaming/moving.
For example with WinSCP scripting the batch file would be like:
winscp.com /log=winscp.log /command ^
"open ftp://username:password#example.com" ^
"cd %_RemoteFolder%" ^
"mv *.* %_NewRemoteFolder%/" ^
"exit"
For details see:
mv command
Converting Windows FTP script to WinSCP FTP script
(I'm the author of WinSCP)
The most direct way to handle this is to use PowerShell. This will make the file copy happen on the FTP host without requiring the data to come to your client before being written back to the server.
Invoke-Command -ComputerName FTPHOST -ScriptBlock { Move-Item -Path C:\dir1\thefile.txt -Destination C:\dir2\thefile.txt }
You can run this from a cmd.exe shell.
powershell -NoProfile -Command "Invoke-Command -ComputerName FTPHOST -ScriptBlock { Move-Item -Path C:\dir1\thefile.txt -Destination C:\dir2\thefile.txt }"

Change the default installation path of SQL Server Management Studio

Can I change the default installation path when installing SQL Server Management Studio that is C:?
My C: drive is full as it has system applications and I want to install SQL Server Management Studio in D: drive. Is this possible?
There is no direct approach (At last now) to change the default SQL Server Management Studio installation path but you can use Symbolic Links:
What are Symbolic Links?
From The Complete Guide to Creating Symbolic Links (aka Symlinks) on Windows :
Symbolic links are basically advanced shortcuts. Create a symbolic link to an individual file or folder, and that link will appear to be the same as the file or folder to Windows even though it’s just a link pointing at the file or folder.
Windows 10 users
Windows 10 users must first enable Developer Mode from
Settings > Update & Security > For Developers.
How To
Open Command Prompt or Windows PowerShell with Run as Administrator and paste this command before installing SQL Server Management Studio
mkdir "D:\Program Files\Microsoft SQL Server"
mkdir "D:\Program Files (x86)\Microsoft SQL Server"
mklink /J "C:\Program Files\Microsoft SQL Server" "D:\Program Files\Microsoft SQL Server"
mklink /J "C:\Program Files (x86)\Microsoft SQL Server" "D:\Program Files (x86)\Microsoft SQL Server"
Now install SQL Server Management Studio (SSMS).
There may be some other file and folder in drive C like
AppData\Local\Microsoft\Microsoft SQL Server but they aren't bigger
than 1GB.
What if already installed SSMS?
Close all instance of SSMS and rename these folders to anything you wish:
C:\Program Files\Microsoft SQL Server
C:\Program Files (x86)\Microsoft SQL Server
Follow How To steps and move the contents of the folders (cut/paste) to the new location
D:\Program Files\Microsoft SQL Server
D:\Program Files (x86)\Microsoft SQL Server
Yes, it is possible starting from SSMS 18.0.
SQL Server Management Studio (SSMS) 18.0 released for general availability
SSMS can be installed in a custom folder – This has been a long standing request. With SSMS 18, you can install SSMS in any folder and the option is available from both command line and the setup UI.
Doing this need updating registry value with use of powershell script and then running the installation, Post installation registry values are reset to default
Update the Value of default installation Directory
$RegKey =”HKLM:\Software\Microsoft\Windows\CurrentVersion”
Set-ItemProperty -Path $RegKey -Name “ProgramFilesDir” -Value “D:\Program Files”
Set-ItemProperty -Path $RegKey -Name “ProgramFilesDir (x86)” -Value ‘D:\Program Files (x86)’
Get-ItemProperty -Path $RegKey -Name “ProgramFilesDir”
Get-ItemProperty -Path $RegKey -Name “ProgramFilesDir (x86)”
Write-Host “1. Run the SSMS installer and wait for its completion… (Start-Process -Wait)” -ForegroundColor Yellow
$process=”D:\Software\SSMS-Setup-ENU.exe”
$args=”/install”
Start-Process $process -ArgumentList $args -Wait
Write-Host “`nProcess `”$process`” has been executed and is now stopped.” -ForegroundColor DarkGreen
Revert the Value to default installation Directory
$RegKey =”HKLM:\Software\Microsoft\Windows\CurrentVersion”
Set-ItemProperty -Path $RegKey -Name “ProgramFilesDir” -Value “C:\Program Files”
Set-ItemProperty -Path $RegKey -Name “ProgramFilesDir (x86)” -Value ‘C:\Program Files (x86)’
Get-ItemProperty -Path $RegKey -Name “ProgramFilesDir”
Get-ItemProperty -Path $RegKey -Name “ProgramFilesDir (x86)”
update the location of icons in start menu to the updated location of the SSMS file.
In my case I had to browse to
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft SQL Server Tools 17
Right click on SSMS and update the target to the new location of SSMS program files and you are all set to go. For detailed instructions
https://sqlx86.com/2018/06/28/installing-ssms-to-a-different-location/
I have earlier given an answer to this post to do this using powershell by editing registry values.
Since then I have tried different things and here I am again with a new way to install SQL Server management Studio from command line to an user desired path.
Steps to do so are as follows
Download latest version of SSMS from this link
Press Win+Q key to open search on your computer and type in cmd, Cick on Run as administrator on the right hand side pane.
Browse to recently downloaded SSMS media from URL in step 1, In my case it was in D:\Software
Use below command to install it to a different folder, In my case I am installing it on D:\test.
“SSMS-Setup-ENU.exe /Install /quiet /norestart /log D:\Test\log.txt SSMSInstallRoot = D:\test”
And you are all set…
For instructions with screenshot do visit
https://sqlx86.com/2018/12/27/change-the-default-installation-path-for-sql-server-management-studio-using-command-prompt/
I followed the instruction given on microsoft support https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-2017
I repaired the Visual Studio 2015 IsoShell and its worked for me.
I'm using 18.8 version (latest) and presto!

Resources