Home » How to Create a File with Variable Name in PowerShell

How to Create a File with Variable Name in PowerShell

To create a file with a variable name in PowerShell, you can use the variable to store the desired name and then pass it to the New-Item cmdlet.

The following method shows how you can do it.

Method 1: Create a file with a variable

# specify the file name 
$fileName = "my_log"

# specify the file path
$filePath = "C:\temp\log\" + $fileName + ".txt"

# create the file

New-Item -Path $filePath -ItemType File

This example creates a text file with a variable name.

The following example shows how you can use this method.

Create a File with a Variable Name in PowerShell

Here’s how you can do it.

# specify the file name 
$fileName = "my_log"

# specify the file path
$filePath = "C:\temp\log\" + $fileName + ".txt"

# create the file

New-Item -Path $filePath -ItemType File

Output:

PowerShell create a file with a variable name
PowerShell create a file with a variable name

The $fileName variable stores the desired file name. The $filePath variable specifies the path and name of the new file, including the variable name $fileName.

Finally, the New-Item cmdlet creates a new file at the specified path with the specified name.

After running the script, PowerShell will create a new file with the specified (based on the variable) at the specified location.

Conclusion

I hope the above article on creating a file with a variable name in PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.