Shoru
Shoru

Reputation: 11

Find file (get content) with variable in file name

I wanted to make a small script for finding and replacing several strings in a file (using a combination of batch and PowerShell). The files are always different, so I'd always need to go into the batch and change the file name of Get-Content and of Out-File. Now I added a prompt to insert the filename and I'm giving this to a parameter, so I could somehow search and edit $filename.txt for example.

Here the normal PowerShell code with replacing just one string (I'll integrate this in one batch file later again):

$filename = Read-Host -Prompt 'Input filename'
(gc $filename.txt) -replace 'foo', 'bar' | Out-File $filename.txt

Since this Script is lying in the same folder like the files I'm not gonna need a path.

I also found out that gc can't read variables, which is exactly my problem here: I'm getting an error code that the argument can't be bound to "path" because it's NULL.

I couldn't find anything else like that, found a lot of Threads on how to out-file variables or how to get file content into a variable but nothing fitting to my case so I'd really appreciate any help from you guys!

Upvotes: 1

Views: 7733

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

PowerShell allows you to use one-word strings or a variable without putting them quotes, so the following two statements will work:

Get-Content foo.txt
Get-Content $filename

However, if you want to use an argument that's constructed of a variable and a string you need to put the expression in double quotes:

Get-Content "$filename.txt"

or use a subexpression for concatenating variable and string:

Get-Content ($filename + '.txt')

With that said, since in your case you're using the filename in more than one place it's probably best to append the extension to your input and use just a variable:

$filename = Read-Host -Prompt 'Input filename'
$filename += '.txt'
(Get-Content $filename) -replace 'foo', 'bar' | Set-Content $filename

Upvotes: 2

Related Questions