using unzip within PowerShell - arrays

Every night we need to zip certain files contained in a folder. I then need to make sure that all the files that should have been zipped are in the zip file.
I have created a piece of code that work perfectly on my PC but when I move the code to the live server I get the following error:-
The term 'unzip' is not recognized as the name of a cmdlet'
I have installed dot.net 4.5 & also the PowerShell Community Extensions 3.1
Here is my code that creates an array of file names:-
$UnZip_Test = unzip -t $ZipFile
$zip_contents = $UnZip_Test | ? { $_ -match "^\s*testing:\s*(.*?)\s+OK\s*$"} | % { $matches[1] }

unzip is not the cmd-let Community Extensions uses. If you had correctly installed the PCE 3.1 you should be able to use Expand-Archive cmdlet.
expand-archive -format zip -path $ZipFile

unzip is not a PowerShell built-in command. You need to provide an unzip.exe in one of the folders in the $env:PATH on the production server, or define a function/cmdlet or alias that does The Right Thing™.

I use this in my powershell scripts, granted it's not powershell but requires java to be installed.
jar xf ./path/to/archive.zip
In my case, knowing java is on a server is a lot easier than downloading some community extension all over the place

Related

How Can I Make This Script Run For All Members of My Team?

I've figured out how to get powershell to check for a running DLL and if it's not running, to run it. I type npm run passthru and the script does the work:
"scripts": {
"passthru": "powershell if (-not (Get-Process -Name MyPassThruApp -ErrorAction SilentlyContinue)) { dotnet run --project C:/git/MyPassThruApp/MyPassThruApp/MyPassThruApp.csproj }",
},
All well and good, but I want the script to work for any member of my team (on Windows). I tried adding the path to the .csproj file to the Path environment variable (and removing it from the script), but that didn't work - it won't run for me, even after restarting the computer.
Suggestions?
Normally 1, as is the case with the dotnet CLI, the PATH environment variable isn't used to resolve file paths for other file types than executables (e. g. .exe, .cmd, .bat, .ps1).
You may create a dedicated environment variable, say MY_CSPROJ_PATH that specifies the path to the project file and then use it like this:
--project $env:MY_CSPROJ_PATH
Alternatively you could use the convention that the project files have to reside in a fixed sub directory of the user's directory, in which case the $env:HOME environment variable could be used:
--project $env:HOME\projects\MyPassThruApp\MyPassThruApp\MyPassThruApp.csproj
[1] As an aside, PowerShell unexpectedly does execute (open with the default shell action) arbitrary files in $env:PATH - see GitHub issue #12632.

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

SQL installed but powershell not picking up sqlps commands (like invoke-sqlcmd)

I installed ms sql server with chocolatey:
choco install SQLServer2012DeveloperEditionWithSP1 -y -f -source 'http://choco.developers.tcpl.ca/chocolatey' -c "$env:WINDIR\temp"
SQL seems to be installed and working well outside of powershell where it doesn't work. I can see the sqlps module with:
Get-Module -listavailable
...
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 1.0 SQLASCMDLETS
Manifest 1.0 SQLPS
The commands seem to be missing though. I don't have invoke-sqlcmd etc. In theory I should get access to them if I install the module but when I try to import-module sqlps but I get an error about not having a sqlserver drive:
PS C:\WINDOWS\system32> Import-Module SQLPS
Set-Location : Cannot find drive. A drive with the name 'SQLSERVER' does not exist.
At C:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules\SQLPS\SqlPsPostScript.ps1:1 char:1
+ Set-Location SQLSERVER:
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (SQLSERVER:String) [Set-Location], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
I know several people in my group who went through these steps and did get the correct sql ps setup working.
Any tips or ideas would be very helpful. Thanks.
Good day,
I am guessing that you are using SQL Server 2017, since this is common issue in 2017, as I will explain below. I am not sure what version is used since this question is a bit old and was asked on May 2 '17 at 22:58
The error that you get includes the basic issue
Set-Location : Cannot find drive. A drive with the name 'SQLSERVER' does not exist.
It does not say that the module 'SQLPS' does not exist, but that the module 'SQLSERVER' does not exist
The explanation is that until 2016 SQLPS module was included with the SQL Server installation, but the PowerShell module which we use is the 'SqlServer' module. 'SqlServer' module was included with SQL Server Management Studio (SSMS) 16.x, but if you are using SSMS 2017 (17.x) then 'SqlServer' module must be installed from the PowerShell Gallery.
The procedure to install it is to execute the command:
Install-Module -Name SqlServer
If you get error like PackageManagement\Install-Package : The following commands are already available on this system:...
Then you can enforce the installation using the parameters: -Force and –AllowClobber
Since I am not familiar with your system, I will NOT advice you what to do or say if you should enforce the installation, but this is the solution which I would probably do in most cases like this (according to the information I noticed in this thread)
Install-Module -Name SqlServer -Force –AllowClobber
In order to confirm that the module is instead you can execute the following command:
Get-Module -Name SqlServer -listAvailable | select Name, ModuleType, Version
Check the version of your installation using the command above, and use it in the following command in order to import the newest version (at the time I write this answer the version is 21.0.17279):
Import-Module SqlServer -Version 21.0.17279
That is all... If all went well then you should be able to use all the SQL Server PowerShell commands
Just a side-note for future readers, I was trying to create a sql backup via powershell. The cmdlets ran as they should under an Administrator account, however running the script under a regular user account, I got the following error:
Cannot find a provider with the name 'SqlServer'
Googling that question brought me here, but the answer to my issue was in a forum post here:
https://social.technet.microsoft.com/Forums/windowsserver/en-US/626bb81a-00ba-4239-ad0a-fec32546350a/check-if-drive-exists-if-not-map?forum=winserverpowershell
I encountered a weird issue and hope that somebody may have a fix for this.
Microsoft SQL Server 2014 (SP2-GDR) (KB4505217) - 12.0.5223.6 (X64) (yeah I know...it's a dev server)
Windows 2012 R2
PSVersion 4.0
I load the SQL assemblies in the PS script
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
The following will fail if I run this immediately after loading the assemblies
Get-ChildItem SQLSERVER:\SQL$env:COMPUTERNAME
Get-ChildItem : Cannot find drive. A drive with the name 'SQLSERVER' does not exist.
If I run the following first, I'm fine.
Invoke-Sqlcmd -Query "SELECT TOP 1 * FROM sys.sysobjects" | Out-Null
Get-ChildItem SQLSERVER:\SQL$env:COMPUTERNAME
I just wanted to amend that I just need to run
Invoke-Sqlcmd | Out-Null
This seems to then fully load the assemblies into memory and everything is OK after.
So I added this to my script:
# SQL cmdlets below need some dll imports from system
# These do not get loaded sometime when running under an non-admin account (Cannof find a provider with the name 'SqlServer')
# Running this dummy command seems to load all needed dlls
# Also see: https://www.sqlservercentral.com/forums/topic/unable-access-sql-provider-in-powershell-without-running-an-invoke-sqlcmd-first
Invoke-Sqlcmd | Out-Null
Seems like valuable information that shouldn't get lost, so I thought i'd post it in the highest SO when googling for that particular error.
One could argue that installing the module rather than this dummy method would be cleaner.
As pointed, here are the links that you should refer now.
MSDN Link
Running SQL Server Powershell
Cannot find path 'SQLSERVER' Issue
There is an answer given by Jarret. Simply loading the module won't help actually. These set of commands have to run after that.
Push-Location
cd $sqlpsPath
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
Update-TypeData -PrependPath SQLProvider.Types.ps1xml
update-FormatData -prependpath SQLProvider.Format.ps1xml
Pop-Location
Hope it helps.

Batch file - Download the latest FTP folder

I'm trying to download the latest folder from an FTP server. This folder contains several folders in which contains several CSV files.
The issue I have is that the folders are created each day and each time I run the script I only want it to download the latest folder at that location.
I have not the foggiest idea of how to specify this, or even download an entire folder structure from an FTP using batch file.
Please let me know if any additional information is required and I will provide it immediately, thanks again for your help.
Kind Regards,
Lewis
There's no easy way to select the most recent folder with the built-in Windows FTP client, the ftp.exe. You would have more luck with a PowerShell script and the FtpWebRequest.
But even if you manage to select the most recent directory, neither the ftp.exe nor the FtpWebRequest support recursive downloads anyway.
You better use some more powerful 3rd party FTP client.
For example with WinSCP FTP client you can download the latest file or folder, using the -latest switch of the get command (WinSCP 5.9 and newer):
winscp.com /command ^
"open ftp://username:password#ftp.example.com/" ^
"cd /remote/path" ^
"lcd c:\local\path" ^
"get -latest *" ^
"exit"
See also the guide to downloading the most recent file with WinSCP.
(I'm the author of WinSCP)

i want to execute a .ps1 powershell script in red hat linux server

i am having a .ps1 powershell script which executes in window, but my whole data is in linux server, is there any possible way via which i can execute the powershell script in red hat server
the powershell script is :
Clear-Host
$path="D:\Deep Backup 26-04-2013\New folder"
$systemname=Read-Host 'Enter System Name'
$files=Get-ChildItem $path -Recurse -Force -Include *_Registrar.zip*,*.reg.zip*
$counter=1
foreach($file in $files)
{
$name=$file.name
[void][system.reflection.Assembly]::LoadFrom("C:\Program Files\MySQL\MySQL Connector Net 6.5.4\Assemblies\v2.0\MySql.Data.dll")
$dbconnect=New-Object MySql.Data.MySqlClient.MySqlConnection
$dbconnect.ConnectionString="server=localhost;userid=root;password=nPr123*;database=test3;"
$dbconnect.Open()
$sql="insert into eid values('"+$name + "','"+$systemname+"')"
$command=new-object MySql.Data.MySqlClient.MySqlCommand($sql,$dbconnect)
$command.ExecuteNonQuery()
}
$sql="insert into eid_unique
select distinct Packet_name, System_name from eid a
where not exists (select 1 from eid_unique b
where a.Packet_name=b.Packet_name);"
$command=new-object MySql.Data.MySqlClient.MySqlCommand($sql,$dbconnect)
$command.ExecuteNonQuery()
$dbconnect.close()
Four years later from original question microsoft releases powershell for linux. And it's opensource: https://github.com/PowerShell/PowerShell
In linux environment you can use syntax like this: (script.ps1, executable)
#!/usr/bin/powershell -Command
write-host -fore Green "executing PowerShell!";
Pash is a cross-platform mono clone of Powershell which is under active development.
You only need to download, build it with xbuild, and run it.
Just like with Powershell on Windows you can execute your script with
& '/path/to/script.ps1'
After installing powershell, easy enough:
thufir#dur:~/powershell$
thufir#dur:~/powershell$ ./hello_world.ps1
hello world
done
thufir#dur:~/powershell$
thufir#dur:~/powershell$ cat hello_world.ps1
#!/usr/bin/pwsh -Command
echo "hello world"
"done"
thufir#dur:~/powershell$
Not sure why it's pwsh and not powershell, but that's Linux for you.
You can also easily install on linux with
snap install powershell --classic
This revision of snap "powershell" was published using classic confinement and thus may perform arbitrary system changes outside of the security sandbox that snaps are usually confined to, which may put your system at risk.
It sounds like Pash may work for you.
I want to share a straightforward approach that helped me. Please follow the official Microsoft documentation for this. There are two steps to this question.
Installing PowerShell (on your OS)
Running the PowerShell script
Installing PowerShell:
Following URLs will assist you to install PowerShell in your machine.
Windows: URL
Linux OSs: URL
MacOS: URL - for direct download option (I used this option)
To confirm your installation, open up a terminal and run pwsh (this is for mac). You will see the following:
Running the PowerShell script:
Next, in the PowerShell terminal, run the following command. Replace my-script.ps1, with your script name:
./my-script.ps

Resources