PowerShell failing in a task sequence
I recently worked on an issue with a customer that might affect more of you out there. They were trying to run a simple PowerShell (POSH) script in a System Center 2012 R2 Configuration Manager SP1 (SCCM/ConfigMgr) OSD task sequence. The PS1 script file would run fine outside of the task sequence, but in the task sequence it was failing. Looking at the logs there was an exit code 4 (The system cannot open the file) being returned. The task sequence was doing a "run command line" step similar to:
- CMD.EXE /C %SYSTEMDRIVE%\windows\system32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -file %SYSTEMDRIVE%\windows\temp\collection\MYPOSH.ps1
Looking a littler deeper in the logs we saw things like:
- gwmi : The term 'Get-WMIObject' is not recognized as the name of a cmdlets, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify the path is correct and try again.
A little time spent troubleshooting and testing reveled that once the OS is laid down but the task sequence is still running the PowerShell system didn't load up all the normal modules you would expect to be available to you. One of those basics that wasn't loaded was the PowerShell Management module, which has all the cmdlets for interaction with WMI. The fix I used was to add a step in the PS1 file to fist import the missing module, in this case the get-WMIObject module (other cmdlets might be in other modules, but the idea is the same). The added line was:
- import-module -Name C:\windows\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Management -verbose
Once that runs all the normal WMI modules are present for the rest of the POSH script to load and use.
7/29 update - Typo fixes