1

If I have 10 *.csv files in a folder, I would like to create an out-file as D:\10.txt I cannot get the syntax right, here's my last attempt:

(Get-ChildItem 'D:\Data\' -File -Include *.csv).Count | Out-File -filepath "D:\test$($_).txt"

I prefer a oneliner due to another system that must call this.

Can somebody help me please ? Many thanks !

2 Answers 2

2

The automatic $_ variable - representing the current input object in each step of a pipeline - can only be used in arguments that are script blocks ({ ... }), not in expandable strings ("...").

A per-input-object script block is most typically used with the ForEach-Object cmdlet, but you can also use it as a delay-bind script-block parameter with pipeline-binding parameters.

While that doesn't work with Out-File, it does with Set-Content, which is generally the right tool to use with strings anyway:

(Get-ChildItem D:\Data -File -Filter *.csv).Count |
  Set-Content -LiteralPath { "D:\test$_.txt" }

Note that I've replaced -Include with -Filter, which is not only more efficient, but also avoids the pitfall of
-Include only applying to the input directory path, not to the items inside it - see this GitHub issue.

Caveat: In Windows PowerShell - but fortunately no longer in PowerShell Core, where (BOM-less) UTF-8 is now consistently used - Out-File and Set-Content use different character encodings by default: UTF-16LE ("Unicode") vs. the system's active ANSI code page ("Default"); use the
-Encoding parameter to specify the desired encoding, as needed.

Sign up to request clarification or add additional context in comments.

Comments

0

I try with this

$files = Get-ChildItem 'D:\Data\*.csv'
$CountFile = $files.Count
touch "D:\$($CountFile).txt

I tried with a powershell emulator from Ubuntu, I hope this can help you. Greeting from Argentina

1 Comment

For me on Windows it doesn't work: The term 'touch' is not recognized as the name of a cmdlet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.