【问题标题】:How to pass two strings to a PowerShell function?如何将两个字符串传递给 PowerShell 函数?
【发布时间】:2021-02-22 06:11:13
【问题描述】:

如何将$dir$file,然后concatenate 传递到单个路径?

输出:

posh> 
posh> pwsh ./worker.ps1
dir is /home/nicholas/powershell/regex a.log
file is 
full is /home/nicholas/powershell/regex a.log/
posh> 

图书馆:

function SearchFile($dir,$file)
{
"dir is $dir"
"file is $file"

$full = [string]::Concat("full is ",$dir,"/",$file)
$full
#$pattern='(?=.*?foo)(?=.*?bar)'
#$string = Get-Content $full
#$result = $string | Select-String $pattern
#$result
}

工人:

. /home/nicholas/powershell/functions/library.ps1


$dir = "/home/nicholas/powershell/regex"
$file = "a.log"

SearchFile($dir,$file)

我似乎为$dir 传递了一个数组,并且没有像预期的那样在SearchFile 中为$file 分配任何内容。

【问题讨论】:

  • 调用函数时,不要在函数参数周围使用()。 [grin] 把它们放在那里,比如SearchFile $dir $file
  • 这工作@Lee_Dailey 谢谢
  • 不客气!很高兴能帮上一点忙……[grin]
  • 是的,信不信由你,我的 Kindle 上有一本 powershell 书。它涵盖了我不需要知道的所有内容..lol。我只是偶然发现了如何像上面那样声明函数。

标签: string function powershell oop concatenation


【解决方案1】:

可以用更简单的方式完成:

function SearchFile ($var_1, $var_2) {
    $full_path = "$var_1/$var_2"
    $full_path # Output --> C:/temp/test.txt
}

$my_dir  = "C:/temp"
$my_file = "test.txt"

SearchFile $my_dir $my_file # Do not use coma when calling a Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 2014-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多