Monday, April 25, 2011

How to Pass a Variable to PowerShell from a DOS Batch File

Update: Many thanks to @ye110wbeard for a much simpler solution to pass the current working directory to a powershell command from a DOS batch file.


Powershell -executionpolicy remotesigned -file %~dp0\YourScript.ps1.


Scott


------------------------------------------------------


I'm sure there is a better way, but here is a way to pass the current directory for an executing batch file to a PowerShell script, to execute a PowerShell script that is in that directory. Then control returns to the batch file. Thanks to Wes' Puzzling Blog for the tip on the %~dp0 trick!





  • Echo the current directory to a text file in the $pshost directory. This is almost always the directory c:\windows\system32\WindowsPowerShell\v1.0.




  • The command to do this in the batch files is:
    echo %~dp0 > c:\windows\system32\WindowsPowerShell\v1.0\currentBatchPath.txt




  • Now start the PowerShell session, read the file contents into a variable. The variable will end in a backslash, so use substring to parse out all but the last character. Then use the Set-Location to change to the batch directory, and execute the PowerShell script.




  • The (ugly) command looks like this:




  • powershell -executionpolicy remotesigned $currentBatchPath=get-content c:\Windows\System32\WindowsPowerShell\v1.0\currentBatchPath.txt;Set-Location $currentBatchPath.substring(0,($currentBatchPath.Length-1));.\YourPowerShellScript.ps1