Bootstrap FreeKB - PowerShell - Create file using New-Item or Set-Content
PowerShell - Create file using New-Item or Set-Content

Updated:   |  PowerShell articles

New-Item can be used to create files and directories. In this example, file example.txt will be created.

New-Item C:\Users\john.doe\example.txt

 

Something like this should be returned.

PS C:\> New-Item C:\Users\john.doe\example.txt


    Directory: C:\Users\john.doe


Mode                 LastWriteTime         Length Name                                                                                                                                                                                                           
----                 -------------         ------ ----                                                                                                                                                                                                           
-a----         4/20/2023  11:05 PM              0 example.txt

 

In this example, directory C:\Users\john.doe\foo wil be created.

New-Item -Path "C:\Users\john.doe" -Name "foo" -ItemType directory

 

I like to put New-Item in a try catch block to have clean output if an exception is raised.

try {
    New-Item -Path "C:\Users\john.doe" -Name "foo" -ItemType directory -ErrorAction Stop | Out-Null
}
catch {
    Write-Warning $Error
}

 

Set-Content can be used to:

  • Create a new file that contains a string of text
  • Update a file that already exists to contain a string of text (overwrite)
try {
    Set-Content C:\Users\john.doe\example.txt "Hello World"
}
catch {
    Write-Warning $Error
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 6dab94 in the box below so that we can be sure you are a human.