1

Is there a way to use a variable whose value contains the colon character as a filename string in a command-line redirect? Powershell always treats the colon as a drive separator, regardless of escape characters. How can this be done using the colon as a character literal contained in the output filename?

Example:

$colonVar = "Colon:string"
echo "fileContents" > "file$colonVar.txt"

yields

Cannot find drive. A drive with the name 'fileColon' does not exist.

Can we instead write "fileContents" to a file named "fileColon:string.txt"?

I have not been successful using any combination of single or double quotation marks, escape characters, parentheses, or dollar sign and parentheses in the string value or the redirect string. The portion of the string after the colon is always treated as a drive.

(Using Powershell 2.0)

1

In Windows you can't have a file with a colon in it's name, so it's not PowerShell that's preventing it, it's the file system. Strip out the colon, and/or replace it with a character that's valid for filenames.

From https://support.microsoft.com/en-us/kb/177506:

A filename cannot contain any of the following characters: 
\ / : * ? " < > | 
| improve this answer | |
  • On the other hand, it can be worked around... well, some: stackoverflow.com/questions/10386344/… – Gombai Sándor Mar 30 '16 at 20:09
  • 1
    Thanks. I assumed from the error message that powershell, not the system, was blocking the command from succeeding but it makes sense that it's blocked at the OS level because the OS doesn't allow it anyway. For the record, powershell supports inline text replacement, e.g. echo "fileContents" > "file$colonVar.txt".replace(":","_") or $colonVar = "Colon:string".replace(":","_") – taz Mar 30 '16 at 20:18
0

You can't do it with redirection or Out-File or Tee-Object in PowerShell as far as I can tell. You can write to a file with a name that has a colon using Set-Content, but that would make it an Alternate Data Stream for the file with the name before the colon. Redirection to these Alternate Data Streams is possible in the command prompt.

Set-Content -Path ".\file$colonVar.txt" -Value "fileContents" works, but if you browse there in the file system you'll only see a file named literally "fileColon" with no colon in the name and no extension and no contents.
If you want to access the stream, you can use Get-Content -Path ".\file$colonVar.txt", but I don't know a way of accessing that stream with most Windows applications.

See my question for how I found this possibility out. Colon in filename creates pseudo folder. How do I see what's inside?

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.