【问题标题】:Creating an Array From String in Powershell在 Powershell 中从字符串创建数组
【发布时间】:2021-01-15 10:47:41
【问题描述】:

我正在通过字符串参数将一个字符串从 Python 传递到我的 powershell 脚本中。该字符串是我需要从一台机器复制到另一台机器的文件列表。我使用 for each 循环来处理此列表中的每个文件。我遇到的唯一问题是我不知道如何用逗号分隔列表。

我用来调用此脚本的 python 如下所示(出于安全原因,删除了一些变量)

fileList = '("\\\\[computerIP]\D$\PI_Backup\pibackup_23-Sep-20_00.15.00.txt", "\\\\[computerIP]\D$\PI_Backup\pibackup_23-Sep-20_12.15.00.txt", "\\\\[computerIP]\D$\PI_Backup\pibackup_24-Sep-20_00.15.00.txt")'

subprocess.run(['powershell.exe', '.\CopyFiles.ps1', '-filelist:', folderPathList, '-computerIP:', computerIP,  '-userName:', userName, '-userPass:', userPass, '-destPath:', destinationPath, '-filepath:', sourcePath])

我在 powershell 中使用的循环如下所示

#Cycles through array copying files over
foreach ($file in $fileList)  

当我使用foreach($file in -split $filelist) 时,我可以用空格分隔我的列表,但它不允许我用逗号分隔。我正在复制的某些文件的名称中可能有空格,因此我需要能够用逗号而不是空格分隔。

我也尝试过foreach ($file in ($fileList -split ',') ),但这似乎只是复制了我数组中的最后一个文件。

【问题讨论】:

  • 因此您将参数传递给 PowerShell 脚本。参数的数据类型是什么?
  • foreach 循环的正文中是否有与问题相关的内容?如果没有,请从问题中摆脱它
  • @Bill_Stewart 这是一个字符串。
  • 这是一个字符串?字符串是如何分隔的?如果,(不推荐),那么可以写( foreach $fileName in ($myParameter -split ',') ) { ...
  • 关于-split 运算符的帮助主题包含很多有用的信息:help about_Split

标签: python arrays string powershell split


【解决方案1】:

我发现问题在于我使用 python 传递文件列表的方式。我在 python 中将值作为数组传递。我需要将它作为一个大字符串传递。在我这样传递它们之后

folderPathList = '("\\\\[computerIP]\D$\PI_Backup\pibackup_23-Sep-20_00.15.00.txt, \\\\[computerIP]\D$\PI_Backup\pibackup_23-Sep-20_12.15.00.txt, \\\\[computerIP]\D$\PI_Backup\pibackup_24-Sep-20_00.15.00.txt")'

而不是这个:

fileList = '("\\\\[computerIP]\D$\PI_Backup\pibackup_23-Sep-20_00.15.00.txt", "\\\\[computerIP]\D$\PI_Backup\pibackup_23-Sep-20_12.15.00.txt", "\\\\[computerIP]\D$\PI_Backup\pibackup_24-Sep-20_00.15.00.txt")'

带有分隔符的分割命令开始工作。

【讨论】:

    猜你喜欢
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    相关资源
    最近更新 更多