Tuesday, July 22, 2014

Cool powershell tricks

Objective:

  • From within script, launch a specific EXE with a number of / switches in the launch command.

Statement:

  • Setting your full command with all switches as a variable and calling it, doesn’t work as you may expect in powershell, instead the way to go is to create multiple variables and then invoke them all at once using “&”.

Example:

  • Required command =
    • "C:\Program Files (x86)\Microsoft Office\Office14\Outlook.exe  /importprf C:\progra~2\micros~2\custom14.prf"
  • To invoke this EXE command string in powershell (define 3 variables ‘$’, then call them all with ‘&’):
    • $Outlook = "C:\Program Files (x86)\Microsoft Office\Office14\Outlook.exe"
    • $OutlookArg1 = "/importprf"
    • $OutlookArg2 = "C:\progra~2\micros~2\custom14.prf"
    • & $Outlook $OutlookArg1 $OutlookArg2

----------------------------------------------------------------------------------------------------------------------------------

Objective:

  • You’re displaying text to the console via ‘write-host’ and you want to control where the word wrap breaks occur

Statement:

  • There are a number of posts discussing word wrapping options for the output from powershell, but to really have the control over the write-host text wrap, you need to leverage “`n”
  • ` is called a “backtick” in powershell, and using it with the ‘n’ character tells powershell to start a new line.
  • This can be called mid-string…

Example:


  • Write-host “This is a sample bit of code to show how`nformating can work”


-----------------------------------------------------------------------------------------------------------------------------
Objective:

  • You need to work with user directories . . . logged on users defined by an obscure value and %username% doesn’t seem to work.

Statement:

  • There are a number of tricks to pull this info, the one I’ve found most effective currently is $env:username
    • This pulls the username of the user currently running the script.

Example:

  • Define as a variable a subdirectory under their local user profile on the server.
  • $Dir = “C:\users\” + $env:username + “\appdata\local\microsoft\outlook”

No comments:

Post a Comment