PowerShell, Programming, Software

Powershell Local File Manipulation Basic Example

In this article I’ll show a super simple example of an MS Powershell script that you can use to check for the existence of a File or Folder on your local system, and then to create a text file with a Date stamp of the current time.

This sort of functionality can be used for a variety of reasons and can be handy when creating simple logging scripts triggered by a windows scheduled service (aka: Windows Task scheduler).

Overview:

The example PowerShell script below is contained in a file I’ve created that is called CheckFileAndDir.ps1 . I have housed it in a directory on my local PC at: c:/work . You may want to change these parameters to your folder structure if you are going to test running it on your system, or you can post it directly into Powershell and run it from there.

When the Powershell script starts, it is set to execute the following logic:

  1. Does a directory exist called c:/work/test
    1. If not, then create this directory with inherited permissions
  2. Does a text file exist called info.txt
    1. If not, then create this text file
  3. Finally, append a line to the text file that includes the current date and time.

The Example code for CheckFileAndDir.ps1

# 1) File name = CheckFileAndDir.ps1
# 2) To run it from a DOS command line or from a batch file, run the following command. Note that it will close your CMD window
# This is the only way to run it and avoid ExecutionPolicy errors
# powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -File CheckFileAndDir.ps1
# 3) First set the ExecutionPolicy to avoid unnecessary permissions problems
Set-ExecutionPolicy unrestricted
$boolPathExists = test-path 'c:/work/test' -PathType Container
if($boolPathExists -eq $false){
# the path does not exist, we must create it
New-Item -ItemType Directory -Force -Path 'c:/work/test'
}
$boolFileExists = test-path 'c:/work/test/info.txt' -PathType Leaf
if($boolFileExists -eq $false){
# the file does not exist, we must create it.
New-Item -ItemType File -Force -Path 'c:/work/test/info.txt'
}
# Let's get the current date and time to output
# Note that the u switch stands for UniversalSortableDateTimePattern, which shows dates as: yyyy-MM-dd HH:mm:ssZ
$strOutText = 'A new test was run on: ' + (Get-Date).ToString('u')
# Now we can append text to the new file
Add-Content -Path 'c:/work/test/info.txt' -Value $strOutText

Gotchas: Problems running from a CMD window

Ok, so I think everyone will agree that the Powershell execution policy logic is painful and has dubious advantages. In the comments of the code above, I’ve included an example command line that will run the .ps1 file from a CMD prompt or from a batch file, while ignoring the execution policy. Alternately, you can try running the CMD window or batch file as administrator.

Here is the command that you can run to execute your Powershell script from a CMD window. Note that you’ll need to run it from the same directory that the file resides in, or else you’ll need to write out the full path.

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -File CheckFileAndDir.ps1

Checking for Files and Folders

In the script itself, we use the test-path command to check for the existence of the file or folder that we are interested in. Note that folders are specified using: -PathType Container, and Files are specified using: -PathType Leaf.

We assign the results of the checks to variables that we then run if…else statements against. In the condition that the file or folder doesn’t exist, we can create it using: New-Item -ItemType Directory for folders and New-Item -ItemType File for files.

I suppose it is a quirk of the Powershell language that the test-path command calls things Container and Leaf, while the New-Item command calls them Directory and File.

Writing to the text file

Finally, we write a new line to our text file using the Add-Content command. This is fairly straight-forward, and we don’t even have to code for a line break to separate our new content, since the command comes with the line-break inbuilt. Just for reference, Powershell accepts escape characters for line-breaks as:

`r`n

Also note that I am writing out the time stamp in a sortable format called UniversalSortableDateTimePattern, which shows dates as: yyyy-MM-dd HH:mm:ssZ. The code for this is little u, which isn’t clearly documented in the official Microsoft documentation.

Wrapping things up

I hope this example has been useful to you. Feel free to write me a note in the comments below if you have any questions or suggestions.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s