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
Comments
- Anonymous
July 27, 2015
Also, why in the world would you use cmd to launch powershell? That makes absolutely no sense. - Anonymous
July 27, 2015
Sorry... leftover from some troubleshooting. - Anonymous
July 29, 2015
There is no "Configuration Manager 2012 R2 SP2". It's either "Configuration Manager 2012 SP2" or "Configuration Manager 2012 R2 SP1" :-) - Anonymous
July 29, 2015
Torsten - Thanks for keeping me honest. Typos will eventually be my downfall. :-) - Anonymous
March 24, 2016
I know this is a little old, but to Jason Sandys -- You'd use CMD to launch powershell in a TS if you need it to run as a different account. That's at least one reason I can think of. - Anonymous
August 09, 2016
The comment has been removed - Anonymous
September 22, 2016
The comment has been removed