【问题标题】:Pass variable from batch to powershell将变量从批处理传递到powershell
【发布时间】:2014-04-18 14:59:04
【问题描述】:

我有一个批处理文件,要求用户输入变量行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

【问题讨论】:

    标签: batch-file powershell


    【解决方案1】:

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

    顺便说一句,ps 有很好的帮助系统。如果您使用help env,它将列出两个相关主题,您可以依次查看这些主题以获取详细信息。

    希望对你有帮助

    【讨论】:

    • 是的,这是一个选项,但通常最好将参数传递给 PS 脚本,这样您就可以通过函数签名来判断脚本依赖于输入的内容。如果直接从 PowerShell 调用,它还会使 PowerShell 脚本更有用。
    • @Rynant 通常是的,但有时您可能会发现您可以控制脚本但不是它的调用/环境,然后它就派上用场了:-)
    【解决方案2】:

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

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

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

    SET ThisScriptsDirectory=%~dp0
    SET PowerShellScriptPath=%ThisScriptsDirectory%file.ps1
    SET /p asset=Enter the asset name
    
    PowerShell -NoProfile -ExecutionPolicy Bypass -file "%PowerShellScriptPath%" "%asset%"
    

    【讨论】:

    • 文件运行 PowerShell 脚本。您可以使用-file 代替从-command 调用文件。
    • PowerShell -NoProfile -ExecutionPolicy Bypass -file "%PowerShellScriptPath%" %asset% 喜欢这个?
    • 如何在 powershell 中引用该变量?
    • 在我给出的示例中,%asset% 的值被传递给$FileName 变量。你可以使用任何你想要的变量名;关键是批处理文件中列出的参数被传递给 .ps1 脚本中的参数变量。如果您的 .ps1 带有两个参数(例如 param($one, $two); write-host "one: $one, two: $two"),您可以使用 PowerShell -file %PowerShellScriptPath% %assetA% %assetB% 从批处理文件中调用它
    • 这就是我现在拥有的,当我尝试调用它时,powershell 行不会显示我的变量资产。浴文件行是 PowerShell -NoProfile -ExecutionPolicy Bypass -file %PowerShellScriptPath% %asset% 然后在我的 .ps 文件中我有 param($asset) Get-Item $asset "The asset tag is $asset" 。但是脚本从不将我输入的资产放入 .bat 文件中
    【解决方案3】:
    param($asset)
    

    这必须是 PowerShell 脚本中的第一行才能运行,否则它将失败。

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多