Tuesday, 13 September 2011

Powershell and COM objects

Do you want to map a drive using Powershell? Easy.

$net = New-Object -ComObject Wscript.Network
$net.MapNetworkDrive("Z:", "\\ComputerName/Share")

Maybe add a network printer?

$net = New-Object -ComObject Wscript.Network
$net.AddWindowsPrinterConnection("\\ComputerName/PrinterName", "Port")

Or create a shortcut?

$shell = New-Object -ComObject Wscript.Shell
$shortcut = $shell.CreateShortcut("example.lnk")
$shortcut.targetpath = "C:\windows\system32\cmd.exe"
$shortcut.save()

A popup for warning or confirmation?

$shell = New-Object -ComObject Wscript.Shell
$shell.popup("Hi",0,"My popup",1)

Then just get the return value to decide what to do next.

Or maybe you want to read a file and want to find out if it contains a specific string?

$fso = New-Object -ComObject Scripting.FileSystemObject
$file = $fso.getfile("C:\example.txt")
$open = $file.OpenAsTextStream(1)
if($open.readall() -match "string"){return $true}

As you can see you can do a lot using Powershell and COM objects.

If you want to know the properties and methods of an object just pipe it to the Get-Member cmdlet.

No comments:

Post a Comment