A bit of PowerShell scripting

Every large deployment has the odd Windows node; well, not every deployment, as many places have Windows-only environments. The reason is quite simple: most closed-source SDKs do not run on anything but Windows, so one needs to write a Windows service to access those functionalities. Fortunately for command-line gurus, Microsoft has created an extraordinary toolset, the PowerShell.

When coding something in PowerShell, one must remember 2 things:

  • The script files should end in .ps1 rather than .bat (and one must usually override a security setting to get the system to run them);

  • Most tasks are one-liners.

Coming from Linux scripting some things may look odd (e.g. it is not possible to directly move directories, one must copy them recursively and then delete the source) but in the end the job gets done. I have put below a few basic tasks that one may at some point need to perform.

1. Getting a zip file from some http server and unzip it:

$source_file = "http://internal.repo/package/module.zip"
$tmp_folder = "C\Temp"
$dest_folder = "C:\Program Files\Internal\Application"

$source_file_name = [io.path]::GetFileNameWithoutExtension($source_file)
$dest_zip = "$tmp_folder\$source_file_name"
  
New-Item -ItemType Directory -Force -Path $temp_folder  
Invoke-WebRequest $source_file -OutFile $dest_zip

New-Item -ItemType Directory -Force -Path $dest_folder
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::ExtractToDirectory($dest_zip, $dest_folder)

Remove-Item -Path "$dest_zip" -Force

### No -Force for the temp folder
Remove-Item -Path "$tmp_folder"

2. Activate and start a new service:

New-Service -BinaryPathName $exePath -Name $serviceName -DisplayName $serviceName -description $serviceDescription -StartupType Automatic 
Start-Service $serviceName

3. Stop and remove a service:

$existingService = Get-WmiObject -Class Win32_Service -Filter "Name='$serviceName'"
if ($existingService) 
{
	Stop-Service $serviceName
	### We should sleep for a few seconds to give time for the service to stop
	Start-Sleep -s 5
	$existingService.Delete()
	### When upgrading an existing service, if we are to put a new binary for the same name, we should also sleep a few seconds here
}

4. Open a firewall port (TCP):

$port = "30000"
$existing_fw_rule = netsh advfirewall firewall show rule name="access to port $port"
if ($existing_fw_rule -match "No rules match")
{
	netsh advfirewall firewall add rule name="access to port $port" dir=in action=allow protocol=TCP localport=$port
}

That’s it on PowerShell for today. Have fun!

Leave a Reply

Your email address will not be published. Required fields are marked *