PowerShell remoting over domain boundaries

Let’s imagine situation when you have server in domain and you want to execute remote PowerShell commands from the client which is not in the domain. Following recipe shows you how to configure client and server for described scenario.

Udemy course: Improve your productivity with PowerShell

On the client run PowerShell commands:

cd wsman:\localhost\Client
Set-Item .\AllowUnencrypted -Value $True -Force
Set-Item .\TrustedHosts -Value * -Force

On the server run PowerShell commands:

Enable-PSRemoting -Force
New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN\Service -Name allow_unencrypted -Value 1 -PropertyType DWORD

On the client switch PowerShell provider to file system and run PowerShell commands to test remoting configuration:

$credential = Get-Credential -Message "Enter credentials" -UserName domain\user
Test-WSMan -ComputerName ServerName -Credential $credential -Authentication Negotiate
Enter-PSSession -ComputerName ServerName -Credential $credential

Note that this configuration is intended only for development or testing purposes and is not intended for production use.

If you are interested in PowerShell automation, take my Udemy course Improve your productivity with PowerShell.

Clean Visual Studio solution using PowerShell

At development sometimes I need to clean Visual Studio solution and remove all builded files of all build configurations (Debug, Release and other custom). To do this task manually means a lot of clicking in Visual Studio UI. To automate this boring task I created following PowerShell script:

param
(
    [string] $solution = "MyProduct.sln"
)

Set-Alias msbuild "${env:ProgramFiles(x86)}\MSBuild\14.0\Bin\MsBuild.exe"

$configurations = @("Debug", "Release")

foreach ($configuration in $configurations)
{
    msbuild $solution /t:clean /p:configuration=$configuration /v:minimal | Out-Null
}

$directories = @("bin", "obj")

foreach ($directory in $directories)
{
    Get-ChildItem -Directory -Recurse | ? { $_.Name -eq $directory } | Remove-Item -Recurse -Confirm:$false
}


Udemy course: Improve your productivity with PowerShell

Script uses following cmdlets:

  • Set-Alias – creates alias for msbuild
  • Out-Null – hides the command output
  • Get-ChildItem – gets the child items (directories) in specified location
  • Remove-Item – removes the specified items (directories)

If you are interested in PowerShell automation, take my Udemy course Improve your productivity with PowerShell.

Configure Microsoft SQL Server using PowerShell

Some time ago I created automatized installation of SharePoint. One of this set of scripts was script for configuration of clean MSSQL installation. Script uses SQL Server Management Objects (SMO) as API for MSSQL manangement:

# Load assemblies
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlEnum") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null

$connection = New-Object Microsoft.SqlServer.Management.Common.ServerConnection
$server = New-Object Microsoft.SqlServer.Management.Smo.Server $connection

# Create login for SP2016\Administrator
$login = New-Object Microsoft.SqlServer.Management.Smo.Login $server, "SP2016\Administrator"
$login.LoginType = [Microsoft.SqlServer.Management.Smo.LoginType]::WindowsUser
$login.Create()
$login.AddToRole("sysadmin")

# Create login for SP2016\SP_Admin
$login = New-Object Microsoft.SqlServer.Management.Smo.Login $server, "SP2016\SP_Admin"
$login.LoginType = [Microsoft.SqlServer.Management.Smo.LoginType]::WindowsUser
$login.Create()
$login.AddToRole("dbcreator")
$login.AddToRole("securityadmin")

# Set max. server memory
$server.Configuration.MaxServerMemory.ConfigValue = 2048
$server.Configuration.Alter()


Udemy course: Improve your productivity with PowerShell

PowerShell script at the start loads SMO assemblies and connects to the local MSSQL instance. Then creates logins from domain accounts and add it to server roles. At the end the script set maximum memory which can MSSQL allocate for ist operation.

If you are interested in PowerShell automation, take my Udemy course Improve your productivity with PowerShell.

Analyse Redis cache usage with PowerShell

At the load tests I need to analyse communication between web servers and Redis Cache. My target was to have a statistics with most accessed cache keys. To get required stasticts I run MONITOR command to collect data from Redis cache usage to file using redis-cli command:

.\redis-cli.exe -h <redis_host> -a <redis_access_key> monitor > monitor.log


Udemy course: Improve your productivity with PowerShell

Then I run load test to create traffic on web servers. After the load test I stop MONITOR command using CTRL+C. Statistics is created from usage of GET command. Raw monitor.log file is processed by following PowerShell command:

Get-Content .\monitor.log `
 | Select-String " ""GET"" " `
 | ForEach-Object { $_.ToString().Split(@(" ""GET"" "), [System.StringSplitOptions]::None)[1] } `
 | Group-Object `
 | Sort-Object -Property Count -Descending `
 | Format-Table -Property Count,Name

Result of PowerShell command is summary statistics with most accessed cache keys:

Count Name
----- ----
 2570 "OrderService_OrderService_Orders_STATE"
 2570 "OrderService_OrderService_Orders"
  261 "Test_a2/product/detail/1"
  225 "Test_a2/product/detail/1HQNnoneV+n+FCDE"
  211 "Test_a2/product/category/1"
  211 "ProductService_ProductService_Product_1_STATE"
  202 "Test_a2/product/detail/1"
  196 "ProductService_ProductService_Product_1"   

If you are interested in PowerShell automation, take my Udemy course Improve your productivity with PowerShell.

Restore Microsoft SQL Server database using PowerShell

In previous post I wrote about the backup of Microsoft SQL Server database using PowerShell. Opposed operation to backup is restore, which can be executed using following PowerShell script:

param
(
    [string] $backupFile = $(throw "Backup file is required"),
    [string] $databaseName = $(throw "Database name is required")
)

$server = "."

Import-Module SQLPS

Invoke-Sqlcmd -ServerInstance $server -Query "ALTER DATABASE $databaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE"
Invoke-Sqlcmd -ServerInstance $server -Query "RESTORE DATABASE $databaseName FROM DISK='$backupFile' WITH REPLACE"
Invoke-Sqlcmd -ServerInstance $server -Query "ALTER DATABASE $databaseName SET MULTI_USER WITH ROLLBACK IMMEDIATE"


Udemy course: Improve your productivity with PowerShell

At the first step database is set to single user mode. Next the restore of database is executed. After restore the database is set back to multi user mode.

If you are interested in PowerShell automation, take my Udemy course Improve your productivity with PowerShell.