将变量从批处理传递到 powershell

ran*_*err 2 powershell batch-file

我有一个批处理文件,要求用户输入变量 line set /p asset=。我像这样调用我的 powershell 脚本

SET ThisScriptsDirectory=%~dp0

SET PowerShellScriptPath=%ThisScriptsDirectory%file.ps

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

我想知道如何从我的批处理文件中向 powershell 发送变量“资产”。

这是我的 .bat 文件内容

@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
Run Code Online (Sandbox Code Playgroud)

Ryn*_*ant 5

如果你有一个file.ps1带有参数的a,

param($asset)
"The asset tag is $asset"
Run Code Online (Sandbox Code Playgroud)

您可以将变量作为参数传递。

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

PowerShell -NoProfile -ExecutionPolicy Bypass -file "%PowerShellScriptPath%" "%asset%"
Run Code Online (Sandbox Code Playgroud)


wmz*_*wmz 5

您可以使用$env:variable_name语法从 powershell 访问当前的 cmd 环境变量。要获取您的变量,您可以使用$env:asset
To try, open cmd, do set "myvar=my value", start powershell, do $env:myvar(这将简单地打印它,但当然您可以将它用作任何其他 ps 变量)

作为旁注,ps 有很好的帮助系统。如果您这样做help env,它将列出两个相关主题,您可以依次检查这些主题以获取详细信息。

希望这可以帮助