【问题标题】:Pass batch variables with spaces in them to powershell script?将带有空格的批处理变量传递给powershell脚本?
【发布时间】:2019-04-11 19:53:24
【问题描述】:

我有一个批处理/powershell 脚本,我用它来列出我所有的电影和电视剧,但遇到了一个小问题,当将批处理变量传递给 powershell 脚本时,我的批处理变量中不能有空格。

我在变量周围尝试了各种 ' 和 " 的组合,但没有任何运气。

我的批处理变量

SETLOCAL enabledelayedexpansion
SET "listfolder=%CD%\ContentList\"

SET "listname1=TVSeries"
SET "RootFolder1=\\SERVER\Storage\TV Series\"
SET "Folder1Width=70"
SET ScanFolder1=TRUE

我的批处理代码运行并将变量传递给 powershell

"%listfolder%Script\Powershell.exe" -executionpolicy remotesigned -File "%listfolder%Script\folder1list.ps1" %RootFolder1% %listname1% %Folder1Width%

我的 powershell 脚本代码来设置变量。

param([String]$RootFolder1, [String]$listname1, [int32]$Folder1Width)

这是我得到的错误,如果我在 %RootFolder1% 路径中有空格,没有空格,所有三个变量都可以很好地传递给 powershell。

C:\Users\hflat\Desktop\Folder Content List Maker v4.5\ContentList\Script\folder1list.ps1 : Cannot process argument
transformation on parameter 'Folder1Width'. Cannot convert value "TV" to type "System.Int32". Error: "Input string was
not in a correct format."

我在这里找到了解决方案How to pass in a string with spaces into PowerShell?

起作用的是使用带有 /S 的 cmd 包装器来解开外部引号并删除我自己的 powershell.exe 路径

cmd /S Powershell.exe -executionpolicy remotesigned -File "%listfolder%Script\folder1list.ps1" "%RootFolder1%" "%listname1%" "%Folder1Width%"

【问题讨论】:

  • 是否可以将批处理脚本重写为powershell?
  • 您尝试单引号还是双引号? '%RootFolder1%' '%listname1%' '%Folder1Width%'
  • 我想这可以做到,但需要一些时间。
  • cmd /S /C Powershell.exe -executionpolicy remotesigned -File "%listfolder%Script\folder1list.ps1" "%RootFolder1%" "%listname1%" "%Folder1Width%" 这确实有效,显然 powershell.exe 本身的路径出现了一些问题。
  • 您想要作为单个参数传递的任何环境变量值都必须包含在"..." 中。你不需要cmd /c 来调用powershell.exe。目前还不清楚您是否还有问题:如果您找到了解决方案,请分享它作为答案,如果您认为未来的读者会感兴趣;如果没有,请考虑删除您的问题。

标签: powershell batch-file


【解决方案1】:

我在这里找到了解决方案How to pass in a string with spaces into PowerShell?

起作用的是使用带有 /S 的 cmd 包装器来解开外部引号并删除我自己的 powershell.exe 路径

cmd /S Powershell.exe -executionpolicy remotesigned -File "%listfolder%Script\folder1list.ps1" "%RootFolder1%" "%listname1%" "%Folder1Width%"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-23
    • 2019-11-19
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    相关资源
    最近更新 更多