Playing Music in PowerShell

email me



# Play a single file
Add-Type -AssemblyName presentationCore
$mediaPlayer = New-Object system.windows.media.mediaplayer
$musicPath = "C:\music\"
$mediaPlayer.open($musicPath + 'PlayMyMusic.mp3')
$mediaPlayer.Play()
exit
 
# Create a playlist of files from folder
# Preview each song for 30 seconds
Add-Type -AssemblyName presentationCore
 
$mediaPlayer = New-Object system.windows.media.mediaplayer
$musicPath = "C:\music\"
$mediaPlayer.open([uri]"$($file.fullname)")

$musicFiles = Get-ChildItem -path $musicPath -include *.mp3,*.wma -recurse

foreach($file in $musicFiles)
{
 "Playing $($file.BaseName)"
  $mediaPlayer.open([uri]"$($file.fullname)")
  $mediaPlayer.Play()
  Start-Sleep -Seconds 30
  $mediaPlayer.Stop()
} 

 
 
Another method

Add-Type -AssemblyName presentationCore
 $filepath = [uri] "C:\Orchestra.mp3"
 $wmplayer = New-Object System.Windows.Media.MediaPlayer
 $wmplayer.Open($filepath)
 Start-Sleep 2 # This allows the $wmplayer time to load the audio file
 $duration = $wmplayer.NaturalDuration.TimeSpan.TotalSeconds
 $wmplayer.Play()
 Start-Sleep $duration
 $wmplayer.Stop()
 $wmplayer.Close()

Copy a File using PowerShell

email me

# Define Source and Target files
$Source = "c:\MyFolder1\TestFile.txt";
$Target = "c:\MyFolder2\TestFile.txt";

# Check to see if $Source exists, if so,
# copy it to $Target
if ([System.IO.File]::Exists($Source))  {
   [System.IO.File]::Copy($Source, $Target)
   "Source File ($Source) copied to ($Target)"
}
else {
"Source file ($Source) does not exist."
}

Office 2016 PowerShell Script

email me

To be used to install Office 2016 64 bit. This has Visio and Project compliance and Office version checks built-in. If a user has a 32bit Visio/Project application, they will be notified to install the Office 2016 32 bit version.

List of required files

scrub2010.vbs – Office scrubber from Microsoft
scrub2013.vbs – Office scrubber from Microsoft
sequence.cmd – see bottom
sequence.ps1 – the powershell script below
Download files

 

Code  view script

## To be used to Install Office 2016
## Files are extracted, setup is ran
## and Office is activated with the KMS

# define variables
$kmsServer = '1.1.1.1' # KMS goes here
$strUser = 'SCCM'
$extractFiles = 'extract.exe' # contains office setup files
$appSetup = 'setup.exe' # use "setup /admin" to create a custom.msp and save to updates folder
$appName = 'Office 2016'
$activateOffice = 'c:\Program Files\Microsoft Office\Office16\ospp.vbs'
$localLog = 'log.txt'
$timeFormat = 'yyyy/MM/dd hh:mm:ss tt'
$msgBox1 = 'This version of Office is not compatible with your computer. Please install the 32 bit version.'
$titleBar1 = 'Office 2016'

# Office 2013
$appVisio2013 = 'c:\Program Files (x86)\Microsoft Office\Office15\VISIO.EXE'
$appProject2013 = 'c:\Program Files (x86)\Microsoft Office\Office15\WINPROJ.EXE'
$checkOffice2013_32 = 'c:\Program Files (x86)\Microsoft Office\Office15\WINWORD.EXE'
$checkOffice2013_64 = 'c:\Program Files\Microsoft Office\Office15\WINWORD.EXE'
$scrubOffice2013 = 'scrub2013.vbs' # scrubber from Microsoft

# Office 2010
$appVisio2010 = 'c:\Program Files (x86)\Microsoft Office\Office14\VISIO.EXE'
$appProject2010 = 'c:\Program Files (x86)\Microsoft Office\Office14\WINPROJ.EXE'
$checkOffice2010_32 = 'c:\Program Files (x86)\Microsoft Office\Office14\WINWORD.EXE'
$checkOffice2010_64 = 'c:\Program Files\Microsoft Office\Office14\WINWORD.EXE'
$scrubOffice2010 = 'scrub2010.vbs' # scrubber from Microsoft

# Used for message boxes
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null

# create event log source
new-eventlog -Logname Application -source $appName -ErrorAction SilentlyContinue
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Created event log source." | out-file -filepath $localLog -Append


# Visio 32 bit Compliance
If (Test-Path $appVisio2013){
[Windows.Forms.MessageBox]::Show($msgBox1, $titleBar1, [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information)
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Visio 2013 32 bit was found" | out-file -filepath $localLog -Append
exit
}Elseif (Test-Path $appVisio2010){
[Windows.Forms.MessageBox]::Show($msgBox1, $titleBar1, [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information)
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Visio 2010 32 bit was found" | out-file -filepath $localLog -Append
exit
}Else{
  # // 32 bit Visio does not exist
}

# MS Project 32 bit Compliance
If (Test-Path $appProject2013){
[Windows.Forms.MessageBox]::Show($msgBox1, $titleBar1, [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information)
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Project 2013 32 bit was found" | out-file -filepath $localLog -Append
exit
}ElseIf (Test-Path $appProject2010){
[Windows.Forms.MessageBox]::Show($msgBox1, $titleBar1, [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information)
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Project 2010 32 bit was found" | out-file -filepath $localLog -Append
exit
}Else{
  # // 32 bit MS Project does not exist
}


Clear-Host 

# Office 32 bit Checker
If (Test-Path $checkOffice2013_32){
#Uninstall Office 2013
Write-Host "Removing Office 2013..."
cmd /c cscript $scrubOffice2013 ALL /Quiet /NoCancel
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Removed Office 2013 32 bit" | out-file -filepath $localLog -Append
 }ElseIf (Test-Path $checkOffice2010_32){
 #Uninstall Office 2010
 Write-Host "Removing Office 2010..."
 cmd /c cscript $scrubOffice2010  ALL /Quiet /NoCancel
 $logstamp = (get-date).toString($timeFormat) ; $logstamp + " Removed Office 2010 32 bit" | out-file -filepath $localLog -Append
}Else{
  # // 32 bit Office does not exist
}

# Office 64 bit Checker
If (Test-Path $checkOffice2013_64){
# Office 2013
Write-Host "Detecting Office 2013..."
# cmd /c cscript $scrubOffice2013 ALL /Quiet /NoCancel
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Detected Office 2013 64 bit" | out-file -filepath $localLog -Append
}ElseIf (Test-Path $checkOffice2010_64){
# Office 2010
Write-Host "Detecting Office 2010..."
# cmd /c cscript $scrubOffice2010 ALL /Quiet /NoCancel
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Detected Office 2010 64 bit" | out-file -filepath $localLog -Append
}Else{
  # // 32 bit Office does not exist
}


# install application
Clear-Host
Write-Host "Extracting Files..."
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " File extract started" | out-file -filepath $localLog -Append
cmd /c $extractFiles
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " File extract completed" | out-file -filepath $localLog -Append
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Exit code: " + $LastExitCode | out-file -filepath $localLog -Append

Clear-Host 
Write-Host "Running Setup..."
cmd /c ($appSetup + $silent)
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Launched setup" | out-file -filepath $localLog -Append
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Exit code: " + $LastExitCode | out-file -filepath $localLog -Append

Clear-Host 
Write-Host "Activating Office..."
cmd /c cscript $activateOffice /sethst:$kmsServer
cmd /c cscript $activateOffice /act
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Activation Complete" | out-file -filepath $localLog -Append
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Exit code: " + $LastExitCode | out-file -filepath $localLog -Append 
If ($LastExitCode -eq 0) {
 
# write event log
Clear-Host
Write-Host "Writing event log..."
$startTime = Get-date
$startLog = $strUser + ': ' + $appName + ' COMPLETED SUCCESSFULLY ' + $startTime
Write-Eventlog -Logname Application -Message $startLog -Source $appName -id 777 -entrytype Information -Category 0
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Installed successfully!" | out-file -filepath $localLog -Append
 
# exiting
Clear-Host
Write-Host "Installed successfully! Exiting now..."
Start-Sleep -s 4
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Exiting..." | out-file -filepath $localLog -Append
}
 
Else
 
{
# write event log
Clear-Host
Write-Host "Writing event log..."
$startTime = Get-date
$startLog = $strUser + ': ' + $appName + ' FAILED SETUP ' 
Write-Eventlog -Logname Application -Message $startLog -Source $appName -id 777 -entrytype Information -Category 0
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Failed setup!" | out-file -filepath $localLog -Append
 
# exiting
Clear-Host
Write-Host "Failed setup! Exiting now..."
Start-Sleep -s 4
$logstamp = (get-date).toString($timeFormat) ; $logstamp + " Exiting..." | out-file -filepath $localLog -Append
}

 

The sequence.cmd for SCCM

@echo on
title SCCM Installation
color 0b

set CurDir=%CD%
set timer=ping -n 10 127.0.0.1

cls
rem check for extract file
if not exist "%CurDir%\extract.exe" exit /b 1
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command "Set-ExecutionPolicy RemoteSigned"
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -file "%CurDir%\sequence.ps1"
%timer%>nul
exit /b 0

VBScript to Return Windows Product Key

email me

This will return the Windows product key in a simple popup. Just save as script.vbs and run.

Code

Set WshShell = CreateObject("WScript.Shell")
MsgBox ConvertToKey(WshShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DigitalProductId"))

Function ConvertToKey(Key)
Const KeyOffset = 52
i = 28
Chars = "BCDFGHJKMPQRTVWXY2346789"
Do
Cur = 0
x = 14
Do
Cur = Cur * 256
Cur = Key(x + KeyOffset) + Cur
Key(x + KeyOffset) = (Cur \ 24) And 255
Cur = Cur Mod 24
x = x -1
Loop While x >= 0
i = i -1
KeyOutput = Mid(Chars, Cur + 1, 1) & KeyOutput
If (((29 - i) Mod 6) = 0) And (i <> -1) Then
i = i -1
KeyOutput = "-" & KeyOutput
End If
Loop While i >= 0
ConvertToKey = KeyOutput
End Function

Testing Some Basics in C# – Part 1 of 2

email me

Part 2

To be used in package design and sequence file creation.


Code – Created in Visual Studio Community 2015 – view code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; //used by Thread.Sleep
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics; //used by Process
using System.Windows.Forms; //used by MessageBox
using Microsoft.Win32; //used by Registry

namespace PlayingAround
{
class ReadAll
{
public static void Main(string[] args)
{
Console.Out.WriteLine("DISPLAY CONTENTS OF A TEXT FILE");

//creates {contents} variabe
string contents = File.ReadAllText(@"C:\test.txt"); 

//outputs {contents} to screen
Console.Out.WriteLine("contents = " + contents); 
Thread.Sleep(5000); //wait 5 seconds

//will wait for {ENTER} key
//Console.In.ReadLine(); 

Console.Out.WriteLine("DISPLAY TIMESTAMP");

//creates {DateTime} variable
DateTime dt = DateTime.Now; 

//outputs {DataTime} to screen
Console.WriteLine("Current Time is {0} ", dt.ToString()); 
Console.Out.WriteLine("");
Console.Out.WriteLine("");
Thread.Sleep(5000); //wait 5 seconds

Console.Out.WriteLine("LAUNCH and KILL PROCESS");
//launch cnn website using IE
Process process1 = Process.Start("iexplore.exe", "www.cnn.com"); 
Thread.Sleep(7000); //wait 7 seconds

foreach (System.Diagnostics.Process IEProc in System.Diagnostics.Process.GetProcesses())
{
if (IEProc.ProcessName == "iexplore")
{
//if IE is found, kill it
IEProc.Kill(); //kill IExplore.exe
}
}

//launch notepad.exe - will stay open
Process process2 = Process.Start("notepad.exe"); 
//wait for process to close before continuing
process2.WaitForExit();                                          
Thread.Sleep(2000); //wait 2 seconds

//show simple popup message - 
//make sure you Add Reference to System.Windows.Forms---under Projects
MessageBox.Show("Program has completed!"); 

//begin event log creation

string sSource;
string sLog;
string sEvent;

sSource = "My Program";
sLog = "Application";
sEvent = "This is the description";

if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog);

EventLog.WriteEntry(sSource, sEvent);
//EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234);
//end event log

//write to text log
string text = "Text1 " + "Text2";
System.IO.File.WriteAllText(@"C:\log.txt", text);

//set registry key
const string userRoot = "HKEY_CURRENT_USER";
const string subkey = "RegistrySetValueExample";
const string keyName = userRoot + "\\" + subkey;
Registry.SetValue(keyName, "MyKeyName", "A_String_Value_Goes_Here", RegistryValueKind.String);

//get registry key
string regValue = (string)Registry.GetValue(keyName, "MyKeyName","");

//show popup message 
MessageBox.Show(regValue);                       

            
//delete registry key
string regDelete = @"RegistrySetValueExample";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(regDelete, true))
{
 if (key == null)
    {
    //does not exist 
    }
 else
    {
     //does exist
      key.DeleteValue("MyKeyName");
     }
   }

        }
    }
}


 

Notes

https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx

Simple Hashtable in PowerShell

email me

Hashtables are a great way to format custom data, change labels on columns, and adjusts column widths.

Code

cls
$TheHashTable = new-object system.collections.hashtable
$TheHashTable += @{"Washington" = "Olympia"; "Oregon" = "Salem"; "California" = "Sacremento" }
$a = @{Expression={$_.Name};Label="Test1";width=15}, `
@{Expression={$_.Value};Label="Test2";width=30}

"The Hashtable contents:"
$TheHashTable | Format-Table $a

 
 
Output (copy and pasted into PowerShell)
 

 
 
Reference

https://technet.microsoft.com/en-us/library/ee692803.aspx?f=255&MSPPError=-2147217396

Acrobat Reader Silent Install using PowerShell

email me

This is the PS code to silently install the Acrobat Reader. I have also added event and local logging, just as demonstrated logging segments.

Code


#define variables
$strUser = "SCCM"
$appSetup = "setup.exe"
$silent = ""
$Source = "Acrobat Reader 15.010.20056"
$TimeFormat = 'yyyy/MM/dd hh:mm:ss tt'
 
#create event log source
new-eventlog -Logname Application -source $Source -ErrorAction SilentlyContinue
$logstamp = (get-date).toString($TimeFormat) ; $logstamp + " Created event log source.">>log.txt
 
#install application
Clear-Host
Write-Host "Starting Setup..."
cmd /c ($appSetup + $silent)
$logstamp = (get-date).toString($TimeFormat) ; $logstamp + " Launched setup.">>log.txt
$logstamp = (get-date).toString($TimeFormat) ; $logstamp + " Exit code: " + $LastExitCode>>log.txt
 
If ($LastExitCode -eq 0) {
 
#write event log
Clear-Host
Write-Host "Writing event log..."
$startTime = Get-date
$startLog = $strUser + ': ' + $Source + ' COMPLETED SUCCESSFULLY ' + $startTime
Write-Eventlog -Logname Application -Message $startLog -Source $Source -id 777 -entrytype Information -Category 0
$logstamp = (get-date).toString($TimeFormat) ; $logstamp + " Installed successfully!">>log.txt
 
#exiting
Clear-Host
Write-Host "Installed successfully! Exiting now..."
Start-Sleep -s 4
$logstamp = (get-date).toString($TimeFormat) ; $logstamp + " Exiting...">>log.txt
}
 
Else
 
{
#write event log
Clear-Host
Write-Host "Writing event log..."
$startTime = Get-date
$startLog = $strUser + ': ' + $Source + ' FAILED SETUP ' 
Write-Eventlog -Logname Application -Message $startLog -Source $Source -id 777 -entrytype Information -Category 0
$logstamp = (get-date).toString($TimeFormat) ; $logstamp + " Failed setup!">>log.txt
 
#exiting
Clear-Host
Write-Host "Failed setup! Exiting now..."
Start-Sleep -s 4
$logstamp = (get-date).toString($TimeFormat) ; $logstamp + " Exiting...">>log.txt
}

 

The wrapper or launch file

This can be used as the main deploy script to wrap and deploy through desktop management software (i.e., SCCM, LANDesk, Altiris, etc.). This should be compiled into one, nice EXE with the resource files.

Code

@echo on
title SCCM Installation
color 0b
cls
 
set CurDir=%CD%
set PSPath=C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
set Timer=ping -n 2 127.0.0.1

%PSPath% -Command "Set-ExecutionPolicy RemoteSigned"
%PSPath% -file "%CurDir%\script.ps1"
%Timer%>nul
exit /b 0

 

List of package source files

abcpy.ini
AcroRdrDCUpd1501020056.msp
AcroRead.msi
AcroRead.mst (made using customization wizard)
Data1.cab
setup.exe
setup.ini
script.ps1 (the PS script from above)
sequence.cmd (the shell script from above)

VLC Player Silent Install using PowerShell

email me

This is the PS code to silently install the VLC Player. I have also added event and local logging, just as demonstrated logging segments.

* if you have trouble with the backtick being recognized as multi-line, just delete it and join the subsequent line.

Code

#define variables
$strUser = "SCCM"
$appSetup = "setup.exe"
$silent =" /S /V/qn"
$Source = "VLC Player 2.2.2"
$TimeFormat = 'yyyy/MM/dd hh:mm:ss tt'

#create event log source
new-eventlog -Logname Application -source $Source -ErrorAction `
SilentlyContinue
$logstamp = (get-date).toString($TimeFormat) ; $logstamp + `
" Created event log source.">>log.txt

#install application
Clear-Host
Write-Host "Starting Setup..."
cmd /c ($appSetup + $silent)
$logstamp = (get-date).toString($TimeFormat) ; $logstamp + `
" Launched setup.exe.">>log.txt
$logstamp = (get-date).toString($TimeFormat) ; $logstamp + `
" Exit code: " + $LastExitCode>>log.txt

If ($LastExitCode -eq 0) {

#write event log
Clear-Host
Write-Host "Writing event log..."
$startTime = Get-date
$startLog = $strUser + ': VLC Player COMPLETED SUCCESSFULLY ' `
+ $startTime
Write-Eventlog -Logname Application -Message $startLog -Source `
$Source -id 777 -entrytype Information -Category 0
$logstamp = (get-date).toString($TimeFormat) ; $logstamp + `
" Installed successfully!">>log.txt

#exiting
Clear-Host
Write-Host "Installed successfully! Exiting now..."
Start-Sleep -s 4
$logstamp = (get-date).toString($TimeFormat) ; $logstamp + `
" Exiting...">>log.txt
}

Else

{
#write event log
Clear-Host
Write-Host "Writing event log..."
$startTime = Get-date
$startLog = $strUser + ': VLC Player FAILED SETUP ' + $startTime
Write-Eventlog -Logname Application -Message $startLog `
-Source $Source -id 777 -entrytype Information -Category 0
$logstamp = (get-date).toString($TimeFormat) ; $logstamp `
 + " Failed setup!">>log.txt

#exiting
Clear-Host
Write-Host "Failed setup! Exiting now..."
Start-Sleep -s 4
$logstamp = (get-date).toString($TimeFormat) ; $logstamp + `
" Exiting...">>log.txt
}

 

The  wrapper or launch file

This can be used as the main deploy script to wrap and deploy through desktop management software (i.e., SCCM, LANDesk, Altiris, etc.). This should be compiled into one, nice EXE with the resource files.

Code

@echo on
title SCCM Installation
color 0b
cls

set CurDir=%CD%
set PSPath=C:\Windows\System32\WindowsPowerShell\v1.0
%PSPath%\powershell.exe -Command "Set-ExecutionPolicy RemoteSigned"
%PSPath%\powershell.exe -file "%CurDir%\script.ps1"
ping -n 10 127.0.0.1>nul
exit /b 0

Listing Directory Contents in Pop up

email me

So, let’s say you want to list the contents of a specific folder, but, you want that list in a pop up. Using VBScript, you can easily direct the output of a dir command into a string, and then that output becomes a pop up.

Code

Dim oExecObject, strDir
Set oShell = CreateObject("WScript.Shell")
Set oExecObject = oShell.Exec("%comspec% /c dir /a")
Do While Not oExecObject.StdOut.AtEndOfStream
strDir = strDir & oExecObject.StdOut.Readline() & vbCrLf
Loop
WScript.Echo strDir

Output of my temp folder