If you use the environmental variables „
TEMP
“ or „TMP
“ you get your personal folder for temporary files, e.g. „C:\Users\Niels\AppData\Local\Temp
“. Both variables gives the same folder name.To get the path of the more general folder of temporary files „
C:\Windows\Temp
“ you can use the environmental variables „SystemRoot
“ or „windir
“ and add the name of the Temp-folder in PowerShell like"$Env:SystemRoot\Temp"
To create a unique and identifiable temporary file I usually add a timestamp to the filename like
.$(("{0:s}Z" -f $([System.DateTime]::UtcNow)).Replace(':', '_')).
The Z is to indicate that the timestamp is UTC. That is timezone Z also called Zulu time.
The Replace method of the formatted String-object is used to get rid of the colons in the standard format. A colon is not acceptep by Windows in a file name.
The name of a temporary file can be created in a single PowerShell statement
$TempFile = "$Env:SystemRoot\Temp\_temp.$(("{0:s}Z" -f $([System.DateTime]::UtcNow)).Replace(':', '_')).ps1"
Writing to the temporary file can be done in PowerShell with the cmdlet
Out-File
or PowerShell redirection operators.The first line can be written without any terms, but the following lines must be added to preserve the existing contents of the temporary file.
The first line, that also creates the temporary file, can be written in PowerShell like
'1st line' | Out-File -FilePath $TempFile
A second line can be added using the cmdlet Out-File like
'2nd line' | Out-File -FilePath $TempFile -Append
A third line can be added with the PowerShell appending redirection operator like
'3rd line' >> $TempFile
With the three examples above a temporary file is created
C:\Windows\Temp\_temp.2013-12-11T15_33_50Z.ps1
The contents of the temporary file is
1st line
2nd line
3rd line
This simple technique can be used to create other temporary Windows files like text files or data (csv) files.
No comments:
Post a Comment