Create a Powershell variable

George Sinkinson 110 Reputation points
2025-12-22T23:49:20.2933333+00:00

In Powershell, I'm trying to set up the $outputPath variable like:

$outputPath = "C:\directory\computer name_date.reg"

where

directory is hardcoded (C:\Temp)

computer name is the computer name from the system (GSINKINSON)

date is in yyyymmdd format from the system (20251222)

so it would look like

$outputPath = "C:\Temp\GSINKINSON_20251222.reg"

To be used with the script below run as administrator:

Define the output file path.

$outputPath = ""C:\directory\computer name_date.reg""

Write-Host "Exporting registry."

The command below uses regedit.exe to export the full registry.

It requires administrative privileges.

Start-Process -FilePath "regedit.exe" -ArgumentList "/E", ""$outputPath"" -Wait -NoNewWindow

Write-Host "Registry export complete."

This is pretty much my first attempt at Powershell scripting ...

Windows for home | Windows 11 | Apps
{count} votes

1 answer

Sort by: Most helpful
  1. Marcin Policht 70,050 Reputation points MVP Volunteer Moderator
    2025-12-23T01:59:45.34+00:00

    You can dynamically build $outputPath in PowerShell by combining a hardcoded directory, the system’s computer name, and the current date in the format you want. You don’t need extra quotes inside the string unless you are trying to escape something, PowerShell handles variable expansion inside double quotes. For your example, it would look like this:

    $directory = "C:\Temp"
    $computerName = $env:COMPUTERNAME
    $date = Get-Date -Format "yyyyMMdd"
    $outputPath = "$directory\$computerName`_$date.reg"
    

    Here, $env:COMPUTERNAME retrieves the computer name from the system, Get-Date -Format "yyyyMMdd" gives the date in the format 20251222, and the backtick before _ is optional but can prevent ambiguity if needed. This will produce something like C:\Temp\GSINKINSON_20251222.reg.

    Then your export part can use $outputPath directly:

    Write-Host "Exporting registry."
    Start-Process -FilePath "regedit.exe" -ArgumentList "/E", "$outputPath" -Wait -NoNewWindow
    Write-Host "Registry export complete."
    

    This avoids double quotes inside quotes, which can confuse PowerShell, and ensures the path is built dynamically for any system and date.


    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.