PoshCode Logo PowerShell Code Repository

Invoke-CmdScript.ps1 by Lee Holmes 5 years ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2176"></script>download | new post

From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes

  1. ##############################################################################
  2. ##
  3. ## Invoke-CmdScript
  4. ##
  5. ## From Windows PowerShell Cookbook (O'Reilly)
  6. ## by Lee Holmes (http://www.leeholmes.com/guide)
  7. ##
  8. ##############################################################################
  9.  
  10. <#
  11.  
  12. .SYNOPSIS
  13.  
  14. Invoke the specified batch file (and parameters), but also propigate any
  15. environment variable changes back to the PowerShell environment that
  16. called it.
  17.  
  18. .EXAMPLE
  19.  
  20. PS >type foo-that-sets-the-FOO-env-variable.cmd
  21. @set FOO=%*
  22. echo FOO set to %FOO%.
  23.  
  24. PS >$env:FOO
  25. PS >Invoke-CmdScript "foo-that-sets-the-FOO-env-variable.cmd" Test
  26.  
  27. C:\Temp>echo FOO set to Test.
  28. FOO set to Test.
  29.  
  30. PS > $env:FOO
  31. Test
  32.  
  33. #>
  34.  
  35. param(
  36.     ## The path to the script to run
  37.     [Parameter(Mandatory = $true)]
  38.     [string] $Path,
  39.  
  40.     ## The arguments to the script
  41.     [string] $ArgumentList
  42. )
  43.  
  44. Set-StrictMode -Version Latest
  45.  
  46. $tempFile = [IO.Path]::GetTempFileName()
  47.  
  48. ## Store the output of cmd.exe.  We also ask cmd.exe to output
  49. ## the environment table after the batch file completes
  50. cmd /c " `"$Path`" $argumentList && set > `"$tempFile`" "
  51.  
  52. ## Go through the environment variables in the temp file.
  53. ## For each of them, set the variable in our local environment.
  54. Get-Content $tempFile | Foreach-Object {
  55.     if($_ -match "^(.*?)=(.*)$")
  56.     {
  57.         Set-Content "env:\$($matches[1])" $matches[2]
  58.     }
  59. }
  60.  
  61. Remove-Item $tempFile

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me