Remote Scripting with Powershell without Remoting. Kind of.

I am in the midst of a project at work where we are deploying NCache as a replacement for AppFabric. NCache has some tools to help automate the administrative side of things, but they all must be run locally on the server. 

I have been using the wonderful PowerShell workaround known as Invoke-WMIMethod to sneak a  process onto a remote server, allowing me to execute local commands on remote servers. Neat. (This is a great tool, and can be used for a laundry list of things, there are examples all over the internet.)

I created mine to activate the client license for NCache on all of the clients. One thing on my wishlist for NCache is a more mature central administration toolkit. Everything is designed to be done one node at a time, a little streamlining could go a long way. Anyways, this license script actually copies a bat file and runs it on the remote server, and then removes it. Fast and efficient. 

$servers = gc C:\scripts\txt\list.txt
$install = "C:\temp\NCache_Activate.bat"

forEach ($server in $servers) {
    
    if (test-connection $server -Count 2 -ErrorAction SilentlyContinue) {

    Copy-Item \NCache_Activate.bat -Destination \\$server\c$\temp

    $Process = Invoke-WmiMethod -class Win32_process -name Create -ArgumentList ($install) -ComputerName $server
    If($Process.ReturnValue -eq "0"){write-host  "$server - Completed successfully"}else{write-host  "$server - Completed UNsuccessfully"}

    Sleep 4

    Get-ChildItem \\$server\c$\temp\NCache_Activate.bat | Remove-Item
    }
    else { Write-Host "$server is offline" }
}

And the contents of the bat file are pretty simple too: (names changed to protect the innocent.)

"D:\Program Files\NCache\bin\NActivate\NActivate.exe" /k licensekey /f firstname /l lastname /e noreply@email.com

This alone saved me about 2 hours of work. I'll take it.