Reputation: 1812
I am trying to get a content of a text file by using Get-Content and I want the value for the -path to be on a variable like so:
$MyFileName = "testfile"
$MyFilePath = "(.\MyFolder\" + $MyFileName + ".txt)"
$ServerList = Get-Content -Path $MyFilePath
But I keep getting the error:
Cannot bind argument to parameter 'Path' because it is null.
It works if I hard code the file path
$ServerList = Get-Content -Path (.\MyFolder\MyFile.txt)
Write-Host $MyFilePath
.\MyFolder\testfile.txt
Upvotes: 4
Views: 9716
Reputation: 1812
I found out that the issue is on using a variable inside a workflow. I was so focused on that block of code that I forgot to look at the bigger picture.
I have the code below which had the issue:
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
It turns out that the issue is that I am not passing the variables correctly to a workflow It should be:
Workflow GetServiceStatus{
param(
$FullFileName
)
It is then called like so
GetServiceStatus $FullFileName
Upvotes: 0
Reputation: 27428
If you look at the variable, the string literally has parentheses in it:
$MyFileName = "testfile"
$MyFilePath = "(.\MyFolder\" + $MyFileName + ".txt)"
$myfilepath
(.\MyFolder\testfile.txt)
This would work:
$MyFileName = "testfile"
$MyFilePath = ".\MyFolder\" + $MyFileName + ".txt"
$myfilepath
.\MyFolder\testfile.txt
You could put the parentheses on the outside, but you don't need to. Or
".\MyFolder\$MyFileName.txt"
Upvotes: 2
Reputation: 7479
here's one way to do what you seem to want. [grin] the 1st part is your code with the very peculiar resulting file name. the 2nd part is broken out into parts that are easier to read/understand/modify.
$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
output ...
(.\MyFolder\testfile.txt)
C:\Temp\testfile.txt
note that your code made a file name that is almost certainly invalid. [grin]
Upvotes: 1
Reputation: 1999
try setting the full file path like
$MyFilePath = "C:\My Folder\My File.txt"
or if you the relative path is really what you want remove the brackets like
$MyFilePath = ".\My Folder\My File.txt"
Upvotes: 1