在PowerShell上使用Get-Content时将变量用作-path

时间:2019-06-20 16:29:13

标签: powershell

我正在尝试使用Get-Content获取文本文件的内容,并且我希望-path的值位于像这样的变量上:

$MyFileName = "testfile"    
$MyFilePath = "(.\MyFolder\" + $MyFileName + ".txt)"
$ServerList = Get-Content -Path $MyFilePath

但我不断收到错误消息:

Cannot bind argument to parameter 'Path' because it is null.

如果我对文件路径进行硬编码,它将起作用

$ServerList = Get-Content -Path (.\MyFolder\MyFile.txt)

Write-Host $MyFilePath
.\MyFolder\testfile.txt

4 个答案:

答案 0 :(得分:2)

如果您查看该变量,则该字符串在字面上带有括号:

$MyFileName = "testfile"
$MyFilePath = "(.\MyFolder\" + $MyFileName + ".txt)"
$myfilepath

(.\MyFolder\testfile.txt)

这将起作用:

$MyFileName = "testfile"
$MyFilePath = ".\MyFolder\" + $MyFileName + ".txt"
$myfilepath

.\MyFolder\testfile.txt

您可以将括号放在外面,但是不需要。或者

".\MyFolder\$MyFileName.txt"

答案 1 :(得分:1)

尝试设置完整的文件路径,例如

$MyFilePath = "C:\My Folder\My File.txt"

或者如果您确实想要相对路径,请删除括号,例如

$MyFilePath = ".\My Folder\My File.txt"

答案 2 :(得分:1)

这是一种执行您想要的操作的方法。 [ grin ]第一部分是您的代码,带有非常特殊的结果文件名。第二部分分为易于阅读/理解/修改的部分。

$YourFileName = "testfile"    
$YourFilePath = "(.\MyFolder\" + $YourFileName + ".txt)"

$BaseName = 'testfile'
$Extension = 'txt'
$FileName = $FileName, $Extension -join '.'
$Directory = $env:TEMP
$FullFileName = Join-Path -Path $Directory -ChildPath $FileName

$YourFilePath
$FullFileName

输出...

(.\MyFolder\testfile.txt)
C:\Temp\testfile.txt

请注意,您的代码所创建的文件名几乎可以肯定是无效的。 [咧嘴]

答案 3 :(得分:0)

我发现问题出在工作流内部使用变量。我太专注于那段代码,以至于忘了看大图。

我下面的代码有问题:

Workflow GetServerStatus{
   $ServerList = Get-Content -path $FullFileName
   $ServiceList = Get-Content service_list.txt
   ForEach -Parallel ($Server in $ServerList){
      InlineScript{
         Get-Service -ComputerName $Using:Server -name $Using:ServiceList
      }
   }
}

#credits to @Lee_Dailey
$Extension = 'txt'
$FileName = $BaseName, $Extension -join '.'
$Directory = '.\server'
$FullFileName = Join-Path -Path $Directory -ChildPath $FileName

GetServiceStatus

事实证明,问题在于我没有正确将变量传递给工作流程 应该是:

Workflow GetServiceStatus{
    param(
        $FullFileName
    )

然后这样称呼

GetServiceStatus $FullFileName