【问题标题】:Get-ChildItem with Multiple Paths via Variable通过变量获取具有多个路径的子项
【发布时间】:2019-10-16 13:54:20
【问题描述】:

这个有点难倒我。我通常觉得 powershell 相当先进,但我根本不明白这个的细微差别。

这行得通

$LogFiles = Get-ChildItem -Path c:\windows\temp\*.log,c:\temp\*.log,C:\programdata\Microsoft\IntuneManagementExtension\Logs\*.log

然而我想做(但不工作)是这样的:

$LogsToGather = "c:\windows\temp\*.log,c:\temp\*.log,C:\programdata\Microsoft\IntuneManagementExtension\Logs\*.log"
$LogFiles = Get-ChildItem -Path "$($LogsToGather)" -Recurse

我尝试过将 VAR 设为数组,我尝试过很多方法来制作字符串。我能够围绕这个问题进行写作,但我对了解该常见描述接受什么数据类型 -path 并能够动态创建它特别感兴趣。

cmdlet 接受逗号描述似乎是一个技巧。可以使用某种数组、哈希表等重新创建它吗?

有人知道吗?

【问题讨论】:

  • 输入参数-Path为字符串数组[System.String[]]。因此,还可以使用 [System.String[]]$LogsToGather = @('', '') 之类的数组传递您的路径

标签: powershell


【解决方案1】:

是的,$LogsToGather 必须是字符串的数组,您的命令才能工作:

$LogsToGather = 'c:\windows\temp\*.log', 'c:\temp\*.log', 'C:\programdata\Microsoft\IntuneManagementExtension\Logs\*.log'

注意以, 分隔的数组元素必须单独引用(见底部)。


Get-Help-Parameter 是检查给定参数期望的数据类型的快速方法:

PS> Get-Help Get-ChildItem -Parameter Path

-Path <String[]>
    Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (`.`).

    Required?                    false
    Position?                    0
    Default value                Current directory
    Accept pipeline input?       True (ByPropertyName, ByValue)
    Accept wildcard characters?  false

String[] 表示 [string] (System.String) 实例的数组 ([]) - 请参阅 about_Command_Syntax

有关Get-ChildItem 的更多信息,请参阅the docs


至于你尝试了什么

$LogsToGather = "c:\windows\temp\*.log,c:\temp\*.log,C:\programdata\Microsoft\IntuneManagementExtension\Logs\*.log"

这会创建一个单个字符串,当传递给Get-ChildItem时,作为一个整体被解释为一个单个路径,这显然不会工作。

注意指定数组的元素不加引号,如:

Get-ChildItem -path c:\windows\temp\*.log, c:\temp\*.log, ...

仅在您将数组作为 命令参数 传递时才受支持,而不是在使用 表达式 创建数组的上下文中,例如$LogsToGather = 'foo', 'bar', ..

原因是PowerShell有两种基本的解析模式——参数模式表达式模式,如this answer中解释的那样, p>

【讨论】:

  • mklement0 您的回答简直令人惊叹。谢谢你。我今天在这里所听到的将对我现在和未来都有帮助。再次感谢!
猜你喜欢
  • 2020-10-02
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 2016-06-27
  • 2020-05-31
相关资源
最近更新 更多