将 Get-ChildItem 与字符串变量一起使用
Using Get-ChildItem with a string variable
我正在使用 Get-ChildItem 来保存与用户输入参数匹配的文件位置。我似乎无法弄清楚(我是 powershell 的新手)如何将字符串变量与 cmdlet 一起使用。
我将在下面的脚本中定义 $search_param。
我试过在 powershell ise 上使用内置调试器,如果有的话,它让我更加困惑。
在这里我发现用 $search_param 的实际值替换 '$search_param' 的使用产生了 csv 输出,但是使用 '$search_param' 给出了没有输出。一些有用的信息可能是我用双引号定义了 $search_param。
导致所有问题的行是:
Get-ChildItem 'C:\Users\USER\' -recurse '$search_param'
$search_param 定义为:
| where { $_.name -like "*peanut*" -or $_.name -like "*butter*" -or $_.name -like "*test*"}
| where { $_.extension -in ".txt",".csv",".docx" }
| where { $_.CreationTime -ge "08/07/1998" -and $_.CreationTime -le "08/07/2019" }
| select FullName | Export-Csv -Path .\SearchResults.csv -NoTypeInformation
有趣的是,在我去吃午饭并回到另一个故事之前,我已经完成了所有工作..
我在我的另一段脚本中使用了 Export-csv,它按预期工作。
我可能触及了一些与我提供的行无关的小东西,因为我认为这应该有效..
每个技术人员的评论:
您可以使用 invoke 表达式 "evaluate or run a specified string as a command and return the results of the expression or command."
Invoke-Expression "Get-ChildItem 'C:\Users\SGouldin\' -recurse $search_param"
根据一些研究,依赖调用表达式并不总是最佳做法。
就我而言,我需要它是因为我试图处理用户输入的方式(一些 weeeeird 字符串 concatenation/joins)。
我正在使用 Get-ChildItem 来保存与用户输入参数匹配的文件位置。我似乎无法弄清楚(我是 powershell 的新手)如何将字符串变量与 cmdlet 一起使用。
我将在下面的脚本中定义 $search_param。
我试过在 powershell ise 上使用内置调试器,如果有的话,它让我更加困惑。
在这里我发现用 $search_param 的实际值替换 '$search_param' 的使用产生了 csv 输出,但是使用 '$search_param' 给出了没有输出。一些有用的信息可能是我用双引号定义了 $search_param。
导致所有问题的行是:
Get-ChildItem 'C:\Users\USER\' -recurse '$search_param'
$search_param 定义为:
| where { $_.name -like "*peanut*" -or $_.name -like "*butter*" -or $_.name -like "*test*"}
| where { $_.extension -in ".txt",".csv",".docx" }
| where { $_.CreationTime -ge "08/07/1998" -and $_.CreationTime -le "08/07/2019" }
| select FullName | Export-Csv -Path .\SearchResults.csv -NoTypeInformation
有趣的是,在我去吃午饭并回到另一个故事之前,我已经完成了所有工作..
我在我的另一段脚本中使用了 Export-csv,它按预期工作。
我可能触及了一些与我提供的行无关的小东西,因为我认为这应该有效..
每个技术人员的评论:
您可以使用 invoke 表达式 "evaluate or run a specified string as a command and return the results of the expression or command."
Invoke-Expression "Get-ChildItem 'C:\Users\SGouldin\' -recurse $search_param"
根据一些研究,依赖调用表达式并不总是最佳做法。 就我而言,我需要它是因为我试图处理用户输入的方式(一些 weeeeird 字符串 concatenation/joins)。