PowerShell tutorial – Creating text (log) file in file system – exploring New-Item CMDLET

Hi All,
Greetings for the day!!! Today new learning so sharing ! SHARING IS CARING 🙂
Also keen to include as much as PowerShell stuff on Knowledge-Junction – making PowerShell Hub – All PowerShell learning at one place
Details / Background / Use Case
- I am working on my SharePoint online project where I need to write some logs to text file from PowerShell script
- I need to write logs either .log file or .txt file
- We have PowerShell script to perform job
- Script suppose to read SharePoint list
- Based on details from SharePoint list, creating a modern communication site
- And few other properties like – adding owners, hiding site title and so on
- So need to maintain log for every functionality / operation – whether it succeeded or any error occurred
- If there is any error then writing exception in error log file
- Requirement is to maintain log files for success and exceptions for each site and details
Because of maintaining log file on file system I need to check how to create file on file system using PowerShell and write the content into it
In this article we will discuss how to create file on file system using PowerShell
Creating file using PowerShell
- For creating text file we are using New-Item CMDLET
- SYNTAX
New-Item
[-Path] <String[]>
-Name <String>
[-ItemType <String>]
[-Value <Object>]
[-Force]
[-Credential <PSCredential>]
[-WhatIf]
[-Confirm]
[<CommonParameters>]
- Basically it creates new item based on value specified in ItemType property
- Following are the possible values for ItemType properties
- File
- Directory
- SymbolicLink
- Junction
- HardLink
- Also, type of item that can be created depend on the location of an item
- In file system, New-Item create files
- In registry, New-Item creates registries and entries
- Example – Creating a log file on given path
New-Item -Name “mysite.log” -ItemType “File”
- If we will navigate on respective file we will see the empty file created as
- If we create file with same name then will get an error as
New-Item -Name "mysite.log" -ItemType "File"
- We can avoid the above exception / error with “-Force” attribute as
New-Item -Name “mysite.log” -ItemType “File” -Force
- We can also specify initial content in file with “-Value” attribute as
New-Item -Name "mysite.log" -ItemType "File" -Value "LIFE IS BEAUTIFULE WITH POWERSHELL"

- Please notice the length attribute, it shows the file have content
- Lets open the file

In next article of PowerShell we will discuss how to write content to file
REFERENCES
Thanks for reading! HAVE a FANTASTIC LEARNING!! LIFE IS BEAUTIFUL 🙂





1 Response
[…] We have detailed article on how to create a file (either empty or with initial content) – PowerShell tutorial – Creating text (log) file in file system – exploring New-Item CMDLET […]