Dimitri Koens on June 21st, 2013

With PowerShell you can kill a process with the Stop-Process cmdlet. While the Get-Process cmdlet let’s you get a listing of processes from a remote machine, sadly Stop-Process doesn’t allow you to connect to a remote machine.

Most possibilities in PowerShell are just .NET and WMI monikers. So as soon as PowerShell doesn’t allow me to do something, most of the time I can find a way of addressing .NET or WMI through PowerShell.

One of my students asked me whether it’s possible to kill a SCOM Console on a remote machine. Here’s how, by using WMI and PowerShell. Just replace ServerX and the name of the process with the correct names.

# one-liner from the PowerShell prompt
(Get-WmiObject Win32_Process -computername 'ServerX' | where { $_.name -eq 'Microsoft.EnterpriseManagement.Monitoring.Console.exe' }).Terminate()

# from a powershell script
param([string]$computername='.')
$a = Get-WmiObject Win32_Process -computername $computername | 
where { $_.name -eq 'Microsoft.EnterpriseManagement.Monitoring.Console.exe' }
$a.Terminate()
Dimitri Koens on June 20th, 2013

Here’s a PowerShell script that allows you to monitor processes on the local or a remote PC. It’s based on the Get-Process cmdlet. It loops every secon, compares changes in the process list and displays them nicely on the screen. It shows a green line when a new process runs and a yellow line when a process quits.

Have fun! And let me know what you think in the comments.ProcessMonitor.ps1

 

Function ProcessMonitor {

<#
.SYNOPSIS
Displays changes in the process list on this or a remote PC.
.DESCRIPTION
Great for monitoring logon/startup scripts, batch jobs, software installations, etc...
Version 1.2, created by Dimitri Koens
.EXAMPLE
ProcessMonitor
Compares changes in the process list every second on the local computer.
.EXAMPLE
ProcessMonitor -Interval 30
Compares changes in the process list for every 30 seconds.
.EXAMPLE
ProcessMonitor -Computername ServerB
Compares changes in the process list on server B. Requires RPC.
#>

param([int]$Interval=1, [string]$Computername='.')

Write-Host "ProcessMonitor (interrupt with Ctrl-C)" -ForegroundColor Cyan

$a = Get-Process -ComputerName $Computername
Do {
  Start-Sleep $Interval
  $b = Get-Process -ComputerName $Computername
  Compare-Object $a $b -Property id -passthru | foreach {
    $msg = "{0:hh:mm:ss} {1,5} pid {2,6:N0}MB vm {3,5:N0}MB ws  {4}  {5}" -f (get-date) , $_.id, ($_.vm/1MB), ($_.ws/1MB), $_.name, $_.path
    if ($_.sideIndicator -eq "=>") { Write-Host $msg -foregroundcolor green  }   # new process running
    if ($_.sideIndicator -eq "<=") { Write-Host $msg -foregroundcolor yellow }   # existing process stopped
  } # foreach
  $a = $b
} while (1 -eq $true)
} # function

ProcessMonitor

Tags:

Dimitri Koens on June 13th, 2013

Here’s a simple troubleshooting guide when running into trouble while using SCCM 2012 Operating System Deployment (OSD). Of course it’s not intended to be 100% complete. Let me know in the comments if there are any important omissions or otherwise…

  • Network connectivity: cabling, VLAN, VMware vSwitch, Hyper-V virtual network
    • Firewall
      • PXE requests: UDP ports 67, 68, 69, 4011
      • OS installation: 69/UDP
    • DHCP Server: lease being used
  • SCCM Administration workspace
    • Site, Configure site components, Software Distribution
      • Network Access account: needs read access to shares containing images and drivers
    • Distribution point properties
      • General: certificate expiration
      • PXE: enabled, allow this DP to respond, enable unknown computer support
      • Multicast: enable multicast
      • Boundary groups
  • SCCM Software Library workspace
    • Drivers for network and storage, distribute
    • Boot image
      • import drivers for network and local disk access, drivers must match boot image (WinPE 2 = Vista+, unrelated to final OS)
      • Properties
        • Customization: enable command support (F8, smsts.log)
        • data source: deploy from PXE
      • distribute
    • Operating System Installer package properties
      • data source refers to OS media
      • Distribution Settings: Allow to be transferred via multicast
      • distribute
    • Task sequence
      • capture image path refers to destination wim image to be created
      • account needs write access
      • deploy to specific collection or unknown computers, purpose available, boot media and PXE
  • SCCM Monitoring workspace
    • Distribution Point Configuration Status: PXE and Multicast columns: enabled
    • System Status, Site Status: site server, distribution point, multicast service point healty
    • System Status, Component Status: SMS_EXECUTIVE, SMS_MULTICAST_SERVICE_POINT healthy
    • Reports, Task sequence*
      • e.g. Last 1000 messages for a specific computer (Errors, warnings and information)
  • Target PC/VM
    • Hyper-V VM: Legacy NIC (not necessary anymore since HV 2012 R2?) connected to correct virtual network
    • boot from NIC in BIOS
    • setupapi.log, netsetup.log
    • WinPE phase
      • ipconfig: check networking, DHCP, network drivers for boot image
      • diskpart | list disk: check mass storage drivers for boot image
      • SMSTS.log: mostly found under \windows\<system32/sysWOW64/temp>, can also be under \smstslog, \_SMSTaskSequence
    • After setup: CCMSetup.log in %windir%\system32\ccmsetup

 

Tags: , ,

Dimitri Koens on March 28th, 2013

In the past I have used different tools to ping a list of computers. One of the nicest was a rather old version of WhatsUpGold. It was quick to install and simple to use.

Now we have PowerShell on almost every Windows computer I wanted to have a solution in PowerShell, so I’m not required to install any dedicated ping software anymore.

Here’s a simple script I wanted to share with you. It allows you to ping several computers at once. When a ping is over a configurable threshold output is displayed in yellow or red.

Enjoy!

Dimitri

 

MultiPing: ping several computers

MultiPing: ping several computers

Function MultiPing {
<#
.SYNOPSIS
Sends a ping to a specified host. Colors the output to indicate latency.
.DESCRIPTION
Version 1.1. Provides a simple network monitoring solution, without the need to install any software.
.EXAMPLE
MultiPing ServerX
Sends a ping to ServerX every second. Repeats forever.
.EXAMPLE
MultiPing ServerX, ServerY, 10.1.1.254, www.google.com
Sends a ping to two servers, the IP address of the default gateway and a webserver on the internet
#>

param($computername="localhost", [bool]$repeat=$false, [int]$PingCritical=8, [int]$PingWarning=4)

Write-Host "Pinging $($computername.count) remote systems, repeat is $repeat. Interrupt with Ctrl-C." -Foregroundcolor green
Write-Host "Thresholds: critical=$PingCritical, warning=$PingWarning" -Foregroundcolor green
Do {
  $computername | foreach {
    $a = Test-Connection $_ -Count 1 -ErrorAction SilentlyContinue
    if (!$?) { Write-Host "$_ --- " -nonewline -fore red }   
    else {
      $msg = "$($a.Address) $($a.ResponseTime.ToString().PadRight(4))"
      if     ($a.ResponseTime -ge $PingCritical) { write-host $msg -nonewline -fore red }
      elseif ($a.ResponseTime -ge $PingWarning)  { write-host $msg -nonewline -fore yellow }
      else                                       { write-host $msg -nonewline }
    }
  }
Write-Host ""
Start-Sleep (1)
} while ($repeat)
}
Dimitri Koens on February 26th, 2013

SCOM 2012 Unleashed

Just received my copy of System Center 2012 Operations Manager (SCOM) Unleashed from SAMS Publishing! First impression: very good. The SCOM 2007 Unleashed book was already great because of the great wealth of information in the book. This books structure is almost the same as the previous.

Don’t be fooled by the title on various websites. On Amazon it’s: System Center 2012 Operations Manager Unleashed (2nd Edition). It’s not a second edition. I think the title has been copy/pasted from the previous release.

Kevin Holman is acting as Technical Editor! :)  And thanks to the writers: Kerrie Meyler, Cameron Fuller and John Joyner.

Recently, I was wondering how much code I would need to do basic hardware and software inventory on several remote systems. After experimenting a little bit I came up with the following line of code:

Get-Content pcs.txt | foreach { Write-Host $_ -f Green; $pc=$_; Get-Content wmi.txt | foreach { Get-WmiObject $_ -ComputerName $pc } }

That’s right! Just one line of code. :-)

I’m reading the computers from a text file (pcs.txt). Then I use a foreach-clause to iterate through the list of pc’s. Write the name of the PC on the screen in green to easily identify which system we’re processing. Then I’m reading the different elements to report on from another text file (wmi.txt). For the current system in the loop I’m running a Get-WmiObject on all the items from the second text file and write that on the screen also.

I have to store the name of the current PC in a variable with the command $pc=$_ because I’m entering a nested loop. Whithin the nested loop $_ get’s filled with the current WMI-class, instead of the current PC. I can still refer to the name of the PC through the $pc variable.

Here are both textfiles. They’re just examples, feel free to supply your own items.
wmi.txt:
Win32_Bios
Win32_LogicalDisk
Win32_OperatingSystem
Win32_Product

 

pcs.txt:

server1
server2

Here’s the same line of code but the using the shortest possible notation:

gc p|%{Write-Host $_ -f Green;$p=$_;gc w|%{gwmi $_ -Co $p}}

Sixty characters! I’m really pushing my luck here doing nasty things like abbreveating parameters (-Co instead of -Computername), using all sorts of aliases (gc for Get-Content, % for ForEach, and gwmi for Get-WmiObject) and using textfiles with a name of just one letter. But hey, for the purpose of writing the shortest line of code, it will do! ;-)

Let’s get serious again. PowerShell chooses a different layout than you would expect. To compensate, just use Out-Default.

Get-Content pcs.txt | foreach { Write-Host $_ -f Green; $pc=$_; Get-Content wmi.txt | foreach { Get-WmiObject $_ -ComputerName $pc | Out-Default } }

With Out-Default you can’t write to a text file anymore. Instead of Out-Default, consider using Out-File to create a report.

Get-Content pcs.txt | foreach { "===== Computer $_ ====="; $pc=$_; Get-Content wmi.txt | foreach { Get-WmiObject $_ -ComputerName $pc } } | Out-File report.txt
 Invoke-Item .\report.txt

When you want to use computers from Active Directory the script becomes a little bit different. Be carefull when running this command in a production environment! Escpecially when it’s large!

Get-ADComputer -filter * | foreach { $pc=$_.dnshostname; Write-Host $pc -f Green; Get-Content wmi.txt | foreach { Get-WmiObject $_ -ComputerName $pc } }

Don’t forget to import the ActiveDirectory module if you’re still running PowerShell 2. PowerShell 3 loads this module automatically for you if it’s installed. Check wheter the AD-module is installed with this command:

Import-Module ServerManager; Get-WindowsFeature RSAT-AD-PowerShell

If you don’t want to use any textfiles at all then use this peace of code:

$wmi = "Win32_Bios", "Win32_LogicalDisk", "Win32_OperatingSystem"
Get-ADComputer -filter * | foreach { $pc=$_.dnshostname; Write-Host $pc -f Green; $wmi | foreach { Get-WmiObject $_ -ComputerName $pc } }

Using the new outputmode of Out-GridView in PowerShell 3 we can list the computers graphically, select several of them, and after the press of the OK button only the selected systems are processed.

Get-ADComputer -filter * | Out-GridView -OutputMode Multiple | foreach { Write-Host $_ -f Green; $pc =$_; Get-Content wmi.txt | foreach { Get-WmiObject $_ -ComputerName $pc } }

And here’s an example script file:

# create a collection of interesting WMI classes
$wmi = "Win32_Bios", "Win32_LogicalDisk", "Win32_OperatingSystem"
# get computers from AD, feel free to change the filter
Get-ADComputer -filter * |   foreach {
  # store the dnshostname for reference in the next loop
  $pc=$_.dnshostname

  Write-Host $pc -ForegroundColor Green

  # send the collection of WMI-classes into the pipe
  $wmi |       foreach {
    # run Get-WmiObject on the computer currently stored in $pc
    Get-WmiObject $_ -ComputerName $pc
  }
}

There are a lot of other interesting WMI-sources. Consider these for your WMI-selection:

Win32_Account
Win32_Battery
Win32_Bios
Win32_BootConfiguration
Win32_ComputerSystem
Win32_DiskPartition
Win32_Environment
Win32_LogicalDisk
Win32_NetworkAdapter
Win32_OperatingSystem
Win32_Printer
Win32_Processor
Win32_Product
Win32_ScheduledJob
Win32_Service
Win32_Share
Win32_TimeZone

Please send me a message if you have any questions.

Good luck!

Dimitri

 

Dimitri Koens on October 22nd, 2012

Today I published an update to my PowerShell Quick Reference: it’s now updated to PowerShell v3. I tried to include most notable new features of PowerShell v3 in the limited space of my Quick Reference. I really try to keep it a 2-page Quick Ref. It contains a complete new section on PowerShell v3 technology, like new modules, PowerShell web access, and improvements on the ISE. Also, I reformatted the Quick Ref to match with the Code Coloring in the ISE.

Get the new Quick Ref here

Please drop me a note on any comments, suggestions, etc… you might have, and I will happily incorporate it in a new version.

Have fun!
Dimitri

Dimitri Koens on October 2nd, 2012

PowerShell 3 has launched! Since september 4th you can download the final (RTM) release of PowerShell 3 from this link:

http://www.microsoft.com/en-us/download/details.aspx?id=34595

Some of the best new features include:

  • Automatic module loading, no more “import-module” required
  • Lot’s of extra modules like DHCP, DNS, iSCSI, NetAdapter, NetTCPIP, Printing, ScheduledTasks, SMB, and many others.
  • Few syntax changes. Get-Process | Where-Object { $_.vm -gt 150MB } can now be written as Get-Process | Where-Object vm -gt 150MB
  • Integrated Scripting Environment (ISE) includes Intellisense, code folding, brace matching, code snippets, block select and much more!
  • Show-Command let’s you use cmdlets in an interactive way.
  • Out-GridView now has a -OutputMode parameter! That’s really awesome! For example: Get-Process | Where vm -gt 150 MB | Kill -confirm can now be written as: Get-Process | Sort vm -Descending | Out-GridView -Outputmode multiple | Kill. This means you don’t have to experiment with the parameters (like the VM-size of 150MB) to get the correct processes. And you can confirm in the GUI! What about the Active Directory recycle bin combined with Out-GridView? I’ll write a post about that very soon.
  • Workflows. This is an excerpt from the documentation: “To author sequences of multi-computer management activities — that are either long-running, repeatable, frequent, parallelizable, interruptible, stoppable, or restartable — as workflows. By design, workflows can be resumed from an intentional or accidental suspension or interruption, such as a network outage, a reboot or power loss.” More info: http://blogs.msdn.com/b/powershell/archive/tags/powershell+workflow/
  • And one of my favorites: PowerShell WebApplication. This installs an IIS website where you can use PowerShell commands through a webbrowser. Internet Explorer required, you think? Google Chrome, Firefox, Safari are all supported!

I would recommend to install PowerShell 3 as soon as possible. If you’re concerned about backward compatibility then stay away from the syntax changes and new modules. But start using the ISE today. It’s awesome!

Dimitri

By the way, there’s also a new alias for select-string: sls. It should have been grep, if you ask me…  ;-)

 

Dimitri Koens on May 24th, 2012
Here are my personal SQL Server Installation Best Practices. Please note: they’re best practices. Maybe most of them can be hulpfull for most situations, in other situations some options must be configured otherwise. Please let me know if you have any questions or suggestions.
  • When using 4 (or preferably more) CPU’s reserve the first core for the operating system. Configure this by opening the server (instance) properties, Processors page.
  • Leave Boost priority off. Only use this option when really needed and you know what you’re doing. For example: when using several instances on the same server or when using another application on the same machine. Configure this by opening the server (instance) properties, Processors page.
  • Reserve 512 MB – 2 GB of Ram for the Operating System. Configure this by opening the server (instance) properties, Memory page. Maximum server memory = Physical memory – reservation. For example: if your server has 16 GB Ram and you reserve 2 GB Ram then Maximum server memory would be 14336 (MB).
  • When you’re not using SQL Server authentication then disable the use of SQL Logins through the server (instance) properties, Security page, Select Windows Authentication.
  • Leave SA disabled. If it’s not disabled, log in with a Windows user as a member of the sysadmin role and disable the SA account. If you want to keep the SA account enabled, at least rename it and document the new name.
  • Change the default backup directory path. Open Rhe registry editor and navigate to: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.2\MSSQLServer\BackupDirectory and supply a path.
  • Place TEMPDB on a separate volume.
  • Create an NDF-file for the TEMPDB database for each CPU core available to SQL Server.
  • Place your data files (MDF/NDF) on a separate volume. Configure the placement of new file  by opening the server (instance) properties, Database settings page.
  • Place your transaction log files (NDF) on a separate volume.
  • Leave Auto create and auto update statistics on, unless a product reconfigures otherwise (e.g. BizTalk).

 

Dimitri Koens on May 21st, 2012

Here’s a list with a feature comparison of the three most popular DB products (imho). Please let me know if you have any  additional information, especially on the Oracle topic.

Product / FeatureMicrosoft SQLOracle RDBMSMySQL
Typical ApplicationsSharePoint, SCOM, SCCM, WSUSOBI, SAPJoomla, WordPress, MyBB, phpBB, Drupal, many open-source
Current VersionSQL Server 201211g5.5.x
HistoryFirst release in 1989, Based on Ingress (1974) / Sybase (1987)19791995
Operating SystemWindows Server, Windows ClientWindows, Unix, LinuxWindows, Unix, Linux, Mac and many more
LicensingClosed-source, proprietaryClosed-source, proprietaryOpen-source GNU-GPL
DriversODBC, JDBC, ADO.NET, OLEDB, Microsoft Visual Studio?ODBC, JDBC, ADO.NET, Microsoft Visual Studio
StandardizedANSI-SQLANSI-SQL
TransactionsYesYesUsing InnoDB storage engine
SchemaYesYesNo
Partial IndexYesYesNo
Computed columnsYesYesNo
FailureUsing MyISAM: UPS required, uninterrupted operation assumed
Active/Active clusteringRead-only on second nodeYes (RAC)No
Graphical Management ToolsYes: Management Studio and BI StudioEnterprise ManagerMySQL Workbench. Toad.
Maintenance Plan WizardYesNo
Job SchedulingYes (Agent)Yes (Oracle Scheduler)v5.1 (Event Scheduler)

References


Dimitri Koens on February 15th, 2012

When you’re using the PowerShell module for Hyper-V from James O’Neill (a.k.a. jamesone) then you’ll find out that many cmdlets don’t accept string collections as variable. Here’s an example:

Import-Module c:\psmodules\HyperV\HyperV.psd1
$Hosts = "HV01,HV02,HV03,HV04"
Stop-VM -VM VM03 -Server $HostsString -Force

Throws this error:
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At c:\psmodules\HyperV\VM.ps1:73 char:26
+             Get-WmiObject <<<<  -computername $Server -NameSpace $HyperVNamespace -Query $WQL | Add-Member -MemberType ALIASPROPERTY -Name “VMElementName” -Value “ElementName” -PassThru
+ CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

The module doesn’t interpret the $HostsString as a collection.

Here’s a possible solution:

Stop-VM -VM VM03 -Server $HostsString.split(",") –Force

What I’ve done is include a split-method to split the string and return it as a collection. Now the command works!

 

Dimitri Koens on January 23rd, 2012

Studying for SQL exam 70-432? Make sure you take training 6231 AND 6232. The Microsoft website doesn’t mention the 6432 training:

http://www.microsoft.com/learning/en/us/exam.aspx?id=70-432#tab3

When you take a look at the learning plan (mentioned on the same webpage) you will find that Microsoft recommends both 6431 and 6432 courses.

The 6432 training contains information on partitioning, triggers, stored procedures, etc. If you’re only following the 6431 training you’ll miss a lot of valuable information to pass the exam!

You can also prepare for the exam by studying this book: MCTS Self-Paced Training Kit (Exam 70-432): Microsoft® SQL Server® 2008 – Implementation and Maintenance. This should contain all the information required to pass the exam.

Good luck!

Dimitri

Dimitri Koens on January 11th, 2012

With DPM 2010 you can create Bare Metal Restore (BMR) backups next to System State backups. These backups can become inconsistent more often than regular backups. This can be because there’s not enough space on the DPM server to provide a BMR backup.

It’s possible to run a test backup so you can see how large a BMR backup actually is. It also tells you what volumes are included in the backup, so you can confirm whether the correct volumes are being backed up (for instance: a D-drive with only a huge pagefile will not be backed up).

Perform the following command on the server you are protecting:

wbadmin.exe start backup -allcritical -backuptarget:\\otherserver\share

Replace otherserver with the name of a server that you can write a test backup to. This is not the server you are protecting. Now confirm the included volumes before starting the actual backup. Start the backup and measure the size of the backup as soon as it’s done. Make sure you have this disk space on the volume of the DPM server.

Don’t forget to enable the Windows Server Backup feature on all Windows Server 2008 and later servers you’re protecting with DPM! This is something the DPM Agent doesn’t do for you but it’s required for a BMR backup.

Dimitri Koens on December 6th, 2011

With the built-in Best Practices Analyzer we can run several tests and implement any out comings. The BPA is incorporated in the Windows Operating System since Windows Server 2008. With PowerShell we can run a BPA-scan, store it as a baseline and compare it with our current situation. Here is a PowerShell script to establish the baseline:

$BpaModel = "Microsoft/Windows/WebServer"
$BaselineFile = "baseline.xml"
Import-Module BestPractices
Invoke-BpaModel $BpaModel
Get-BpaResult $BpaModel | Export-CliXML $BaselineFile

And using this script we can compare the current situation with our baseline:

$BpaModel = "Microsoft/Windows/WebServer"
$BaselineFile = "baseline.xml"
Import-Module BestPractices
Invoke-BpaModel $BpaModel
$Bpa = Get-BpaResult $BpaModel
$BpaBaseline = Import-CliXML $BaselineFile
Compare-Object $BpaBaseline $Bpa -property Severity, Title, Resolution |
     Where { $_.SideIndicator -eq "=>" }

You can replace the first line of both script with the name of your model, for example: Microsoft/Windows/DNSServer. You can query for all the installed BPA models using Get-BpaModel. Popular Best Practices that are included with Windows are: Active Directory, DNS and IIS.

I can recommend you schedule the second script every week or so, and e-mail the results as soon as a change is detected.

Dimitri

Dimitri Koens on November 25th, 2011

Hi all,

I just finished work on my all-new Hyper-V Quick Reference. It contains a lot of information I got when using and implementing Hyper-V and teaching it at Microsoft Learning Partners like Global Knowledge, Compu’Train, Twice, New Horizons and Centric. Although this document is best used as a quick reference in practice, it can also be used as a great preparation for Exam 70-659 TS: Windows Server 2008 R2, Server Virtualization.

Please send me a message and let me know what you think of the Hyper-V Quick Reference. You can contact me with questions, remarks, etc regarding this document. Join me on Linked in and Facebook to receive valuable information regarding PowerShell, SCOM, SQL Server and Virtualization.

Get the Hyper-V Quick Reference here: Hyper-V Quick Reference v2-00

Dimitri

Dimitri Koens on November 19th, 2011

It’s official! Since the start of my new website and blog I had 1024 visitors in the first month! Thanks to everyone that left a nice comment or sent me a message by e-mail or Linked In. A lot of people downloaded the PowerShell Quick Reference. I hope it helps them with their first PowerShell encouter.

Some statistics:

  • The PowerShell Quick Reference has been downloaded 500 times!
  • Bing is responsible for 30% of the visitors finding my website by a search engine (so Bing works!).
  • 30% of all the visitors is from the United States.
  • I had two visitors from Vietnam. I have been there only one time, so let’s hope I can even that one out, one time… ;-)

A lot more is coming: several other Quick References are in the making. You can expect a lot more blog posts and even videos. So maken sure you check out www.dimensionit.tv often.

Did you know you can subscribe to the RSS feed?

Hope to see you soon!

Dimitri

Dimitri Koens on November 17th, 2011

There are some situations where you want to boot a remote computer that’s powered off, but don’t have the tools to do that. For example: Microsoft SCCM allows you to boot a remote computer (wake it up from power off) to install Windows Updates. If you don’t have SCCM, there are hundreds of alternative software solutions. I just don’t want to install any peace of software.

Look no further! We can power on remote computers through PowerShell! The script demonstrates how to remote boot a PC with a UDP packet we’re creating through the System.Net.Sockets.UdpClient programming interface (part of dot Net).

Just replace the MAC-address with the address of the computer you want to boot, start the script, and boot!

$MacAddress = [byte[]](0x00, 0x25, 0xB3, 0x0D, 0xA8, 0xF9)
$UDPclient = New-Object System.Net.Sockets.UdpClient
$UDPclient.Connect(([System.Net.IPAddress]::Broadcast),4000)
$packet = [byte[]](,0xFF * 102)
6..101 | foreach { $packet[$_] = $MacAddress[($_%6)]}
$UDPclient.Send($packet, $packet.Length)
Dimitri Koens on November 16th, 2011

PowerShell provides some commands to manipulate services, but that doesn’t work on remote computers! The script you can find below demonstrates that stopping a service on a remote computer using Stop-Service is not working.

First I verify that the MSDTC service is running on the local machine and a remote machine: server2. If I want to stop the service on both machines I use the Stop-Service cmdlet. But this command doesn’t work on server2 when I’m piping the output from Get-Service to Stop-Service!  :-(

There are two solutions. The first is you can use the InputObject parameter as part of Stop-Service.

You can also use WMI to stop a remote service.  Just retreive the specific service from a remote computer by using the Get-WmiObject cmdlet and use the StopService method to stop the service.

WMI is intended to work remote so this command gives the correct result!  :-)

"Verifying services"
Get-Service MSDTC
Get-Service MSDTC -computer server2
"Stopping services"
Get-Service MSDTC | Stop-Service
Get-Service MSDTC -computer server2 | Stop-Service   # Stop-Service does not accept pipelined input!
"Verifying services."
Get-Service MSDTC
Get-Service MSDTC -computer server2
"Stopping remote service, alternative"
Stop-Service -InputObject (Get-Service MSDTC -ComputerName server2)
"Stopping remote service using WMI"
(Get-WmiObject win32_service -computer server2 | Where { $_.name -eq 'MSDTC' }).stopservice()

Thanks to Martin Tengvall for pointing out the -InputObject variant.

Dimitri Koens on November 15th, 2011

It’s possible to compress a folder or file since Windows NT. It’s a feature of the NTFS-filesystem. Normally we would do that on the properties of the folder or file in the Windows Explorer, but you can do this with PowerShell too! Just use this command:

Invoke-WmiMethod -Path "Win32_Directory.Name='C:\Test'" -Name compress

And to Uncompress the same folder, use this command:

Invoke-WmiMethod -Path "Win32_Directory.Name='C:\Test'" -Name uncompress

We’re talking about NTFS compression here, not the ZIP-feature introduced in Windows XP and later. You can notice that the folder is compressed by the blue color of the folder in Windows Explorer. Or you can open the properties of the folder to see whether the size on disk is smaller than the normal size. Do not try to compress items that are already compressed, like pictures (JPG…), music (MP3…), video (AVI, MPG…).

When you use WMI to execute operating system functions like this, you get a return value. When the return value is 0 (zero) this means the command functioned. Other return values can mean different things (read-only, no disk space, no permissions,…). In general: when we’re executing WMI-commands we’re allways checking the return value. You could implement it like this:

$a = Invoke-WmiMethod -Path "Win32_Directory.Name='C:\Test'" -Name compress
If ($a.returnvalue) -eq 0 { "Items successfully compressed" } else { "Something went wrong!" }

 

Dimitri Koens on November 13th, 2011

The other day I stumbled upon a nice PowerShell command to use the speech API found on modern Windows Operating Systems. With this script PowerShell can talk to you! Great for situations where you want to hear about the progress of your script. Or maybe to tell you there’s an alert instead of showing the alert. Here’s the script:

 

$a = New-Object -COM SAPI.SpVoice
$a.speak("I'm completely operational, and all my circuits are functioning perfectly.")