rangerr
rangerr

Reputation: 271

Pass variable from batch to powershell

I have a batch file that ask the user for a variable line set /p asset=. Im calling my powershell script like this

SET ThisScriptsDirectory=%~dp0

SET PowerShellScriptPath=%ThisScriptsDirectory%file.ps

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%'";

Im wondering how i send powershell the variable 'asset' from my batch file.

Here is my .bat file content

@Echo off  
cls
Color E
cls

@echo Enter asset below
set /p asset=

@echo.
@echo your asset is %asset%
@echo.
goto startusmt

:startusmt
@echo.
@echo executing psexec ...
@echo.

SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%RemoteUSMT.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -file %PowerShellScriptPath% %asset%
psexec \\%asset% -u domain\username -p password cmd 

goto EOF

:EOF 
PAUSE

Upvotes: 4

Views: 20510

Answers (3)

Srid
Srid

Reputation: 1

param($asset)

This has to be the very first line in the PowerShell script for it to work, else it will fail.

Upvotes: -1

Rynant
Rynant

Reputation: 24293

If you have a file.ps1 that takes a parameter,

param($asset)
"The asset tag is $asset"

You can pass in the variable as an argument.

SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%file.ps1
SET /p asset=Enter the asset name

PowerShell -NoProfile -ExecutionPolicy Bypass -file "%PowerShellScriptPath%" "%asset%"

Upvotes: 5

wmz
wmz

Reputation: 3685

You can use $env:variable_name syntax to access curent cmd environment variables from powershell. To get hold of your variable you'd use $env:asset
To try, open cmd, do set "myvar=my value", start powershell, do $env:myvar (this will simply print it, but of course you can use it as any other ps variable)

Just as a sidenote, ps has good help system. If you do help env it will list two relevant topics which you can examine in turn to get detailed information.

Hope this helps

Upvotes: 6

Related Questions