Creating a Folder for Each Month Using PowerShell

for ($i=1; $i -le 12; $i++) { md ("2015-{0:d2}" -f $i) }
Advertisements

Starting Minecraft Server (or another program) remotely

I wanted a quick way of starting a Java program (Minecraft Server) from client computers, and the first solution that came to mind was PowerShell remoting. While this is great for background processes, Minecraft Server has a user interface, and so does the NoIP dynamic DNS client, which I am using. The solution was to create a task using task scheduler, and starting this task with PowerShell.

image

This action starts powershell.exe with a script as argument: C:\Mojang\Minecraft_server\StartMinecraftServer.ps1

The script looks like this:

$proc = Get-Process | where { $_.Name -eq "DUC40" }
if ($proc -eq $null) { Start-Process "C:\Program Files (x86)\No-IP\DUC40.exe" }

$proc = Get-Process | where { $_.Name -eq "java" -and $_.MainWindowTitle -eq "Minecraft server" }
if ($proc -eq $null) { Start-Process "C:\Program Files\Java\jre7\bin\java.exe" -ArgumentList "-Xms512m", "-Xmx1024m", "-jar", "minecraft_server.1.8.zip" }

As you see, it checks if “DUC40” (NoIP dynamic DNS client) is started, and if not, starts it. The same goes for Minecraft itself.

Then, I have another scheduled task, which runs at 00:00 each night and starts a script which stops these processes if they are running:

$proc = Get-Process | where { $_.Name -eq "java" -and $_.MainWindowTitle -eq "Minecraft server" }
if ($proc -ne $null) { Stop-Process $proc }
$proc = Get-Process | where { $_.Name -eq "DUC40" }
if ($proc -ne $null) { Stop-Process $proc }

On the client side, the following command needs to be run once from an elevated PowerShell console. (I would like to use the server name rather than the IP address, but it didn’t work for me.)

# The following is needed on the client if computers are not domain joined. It must be run from an elevated process.
Set-Item "wsman::localhost\Client\TrustedHosts" "htpc-dator"
Set-Item "wsman::localhost\Client\TrustedHosts" "192.168.0.101"
Restart-Service WinRM

Then, the following PowerShell script is used to start the task on the server:

# On the server, you must run Enable-PSRemoting.
# Invoke-Command -ComputerName "htpc-dator" -ScriptBlock { Start-ScheduledTask -TaskPath "\Henrik" -TaskName StartMinecraftServer }
Invoke-Command -ComputerName "192.168.0.101" -ScriptBlock { Start-ScheduledTask -TaskPath "\Henrik" -TaskName StartMinecraftServer } -Credential htpc-dator\htpc