PowerShell: Finding Current Script Path

Here’s a useful function that you can paste into your scripts. It will tell you the current location the script is executed from. function Get-ScriptDirectory{ $Invocation = (Get-Variable MyInvocation -Scope 1).Value try { Split-Path $Invocation.MyCommand.Path -ea 0 } catch { Write-Warning ‘You need to call this function from within a saved script.’ } } Get-ScriptDirectory…

Continue Reading

PowerShell: Finding Built-In Administrators Group

Using System User or group names like ‘Administrators’ in scripts may not always be a good idea because they are localized and may not work on machines that use a different UI language. Here is a rather long one-liner that always returns the name of the local Administrators group, regardless of current culture settings: (New-Object…

Continue Reading

PowerShell: Stopping Services Remotely

Stop-Service cannot stop services remotely. One easy way of doing so is Set-Service: Set-Service -Name Spooler -Status “Stopped” -ComputerName targetcomputer However, unlike Stop-Service, Set-Service has no -Force parameter, so you cannot stop services if they, for example, have running dependent services. If your infrastructure supports PowerShell Remoting, you could use Invoke-Command instead: Invoke-Command { Stop-Service…

Continue Reading