Sunday, August 13, 2023

PowerShell (failure): New-TemporaryFile Cannot Create a New Filename without Creating a File

In PowerShell the standard way to create a temporary filename is to invoke the System.IO namespace's Path class's GetTempFileName method. To be clear, only a filename is retrieved and no actual file is created. An example of GetTempFileName being invoked by PowerShell is as follows:

[string] $tempFilenameFromCsharp = ` 

The results of the code above will vary because the filename is randomly generated and the method uses a user's environment variable, $env:TEMP. An example of the value assigned to $tempFilenameFromCsharp when the code snippet above being invoked is as follows:


The New-TemporaryFile PowerShell cmdlet creatse a new temporary file and returns a corresponding instance of the System.IO.FileInfo class whihc include information such as the name of the file created.

My theory that I felt had a 20% chance of working: Invoke New-TemporaryFile with the -WhatIf command-line option and instead of creating a temporary file, the comdlet will return the name of the temporary file that would have been created.

For those that need a reminder, the WhatIf command-line option is defined as follows (see: WhatIf Switch):

My attempt to use New-TemporaryFile to create filename without creating a file was as follows:

[System.IO.FileInfo] $tempFilenameFromPowerShell = `
                         New-TemporaryFile -WhatIf -ErrorAction Stop

The output from invoking the above command is follows:

The following code tests if the $tempFilenameFromPowerShell variable is assigned to $null:

Since $tempFilenameFromPowerShell is set to $null so New-TemporaryFile combined with -WhatIf does not create a new filename. 

Not every idea we try works.

No comments :

Post a Comment