Creating PowerShell Web Server

All Versions

Here is an example that implements a simple web server with just a few lines of code. When you run this script, you can enter one of these URLs into any web browser on your machine:

http://localhost:8080/

http://localhost:8080/services

And here is the code:

# enter this URL to reach PowerShell’s web server
$url = 'http://localhost:8080/'

# HTML content for some URLs entered by the user
$htmlcontents = @{
  'GET /'  =  '<html><body>Here is PowerShell</body></html>'
  'GET /services'  =  Get-Service | ConvertTo-Html

}

# start web server
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add($url)
$listener.Start()

try
{
  while ($listener.IsListening) {  
    # process received request
    $context = $listener.GetContext()
    $Request = $context.Request
    $Response = $context.Response

    $received = '{0} {1}' -f $Request.httpmethod, $Request.url.localpath
    
    # is there HTML content for this URL?
    $html = $htmlcontents[$received]
    if ($html -eq $null) {
      $Response.statuscode = 404
      $html = 'Oops, the page is not available!'
    } 
    
    # return the HTML to the caller
    $buffer = [Text.Encoding]::UTF8.GetBytes($html)
    $Response.ContentLength64 = $buffer.length
    $Response.OutputStream.Write($buffer, 0, $buffer.length)
    
    $Response.Close()
  }
}
finally
{
  $listener.Stop()
}

Please note that the listener runs in an endless loop. When you abort the script, it takes another web request from a web browser for PowerShell to return to you.

Twitter This Tip! ReTweet this Tip!

Changing Password

All versions

Here is a simple way how an existing user can change the password for his account. The user must know his old password and does not need Administrator privileges. Make sure you change the user details at the beginning of this script:

$username = 'yourUserName'
$domain = 'test.lab'

$oldPassword = 'OldPassword'
$newPassword = 'NewPassword'

$sourceCode = @'
[DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
public static extern bool NetUserChangePassword(string domain, string username, string oldpassword, string newpassword);  
'@

Add-Type -MemberDefinition $sourceCode -Name 'Api' -Namespace 'Win32'

[Win32.API]::NetUserChangePassword($domain, $username, $oldPassword, $newPassword)

Twitter This Tip! ReTweet this Tip!

Opening PowerShell for Folder

Any version

If you browsed to a folder using File Explorer, and then would like to open a PowerShell with the current folder set to the browsed folder, just click the address bar in File Explorer, and replace the path with the “powershell” command.

This only fails if the folder called “powershell” exists, in which case File Explorer will switch to this folder rather than opening a PowerShell console.

You can also enter “powershell_ise” into the File Explorer address bar to open the PowerShell ISE with the current folder set as default.

Twitter This Tip! ReTweet this Tip!

Getting GIT tips online

Here is an example that illustrates how you access a REST API online. The script retrieves GIT tips. GIT is an open-source control system. Even if you are not particularly interested in GIT, the code may still be valuable to access other similar REST APIs available on the internet:

#requires -Version 3 

$url = 'https://raw.githubusercontent.com/git-tips/tips/master/tips.json'
$tips = Invoke-RestMethod -Uri $url 
$tips | Out-GridView -Title 'Tips from git-tips' -OutputMode Multiple

Twitter This Tip! ReTweet this Tip!

Creating Shortcut Drives

All PowerShell Versions

Simply add a new drive to one of the file locations you often visit:

# create folder if it does not exist yet
$path = "$homeDocumentsScripts"
$exists = Test-Path -Path $path
if (!$exists)
{
  $null = New-Item -ItemType Directory -Path $path
}

# create new scripts: drive
New-PSDrive -Name scripts -PSProvider FileSystem -Root "$homeDocumentsScripts"

dir scripts:

New-PSDrive creates drives to all the locations you need to access frequently. Note that drives created with New-PSDrive are available in PowerShell only. The new drive is available only in the current PowerShell session. You may want to place this command into your profile script (path to a profile script is found in $profile and may need to be created if it does not yet exist).

Twitter This Tip! ReTweet this Tip!

Running PowerShell Tasks with Progress Bar

PowerShell 2+

Sometimes it may take some time for a PowerShell command to complete, and while the command is working, the user gets no visual clue.

Here is a simple function that uses a background thread to execute long-running commands. In the foreground, it displays a progress bar. If the user decides to abort by pressing CTRL+C, the function terminates the background thread.

function Invoke-WithProgressBar
{
  param
  (
    [Parameter(Mandatory)]
    [ScriptBlock]
    $Task
  )
  
  try
  {
    $ps = [PowerShell]::Create()
    $null = $ps.AddScript($Task)
    $handle = $ps.BeginInvoke()
  
    $i = 0
    while(!$handle.IsCompleted)
    {
      Write-Progress -Activity 'Hang in...' -Status $i -PercentComplete ($i % 100)
      $i++
      Start-Sleep -Milliseconds 300
    }
    Write-Progress -Activity 'Hang in...' -Status $i -Completed
    $ps.EndInvoke($handle)
  }
  finally
  {
    $ps.Stop()
    $ps.Runspace.Close()
    $ps.Dispose()
  } 
}

Just try it:

 
PS> Invoke-WithProgressBar -Task { Get-Hotfix }
 

Twitter This Tip! ReTweet this Tip!