powershellrunonce

RunOnce another file in same folder as first file


I have a folder that holds 4 PowerShell files each with their own 4 exes to call. I am trying to have the 1 PowerShell file write to the registry the runonce key 2nd script, and then propagate down. So far I have successfully done one script and one exe leaving me 3 more to go. I did write a runonce key with a variable $cwd which is $PSScriptRoot but it won't populate the path in the key. It appears as:

This is how the registry entry looks like for run once.

"powershell.exe -noexit "$cwd\main2.ps1" -ArgumentList "-path $cwd""

I want the registry entry to look like this:

"powershell.exe -noexit "C:\Test\test\main2.ps1" -ArgumentList "-path C:\Test\test""

Any ideas how I can pass the path into the script from a variable in my first powershell script.

I tried it and only got one script and exe running, additionally I was able to write to the registry the next key but it wouldn't run the next script.

Better version:

"powershell.exe -noexit -File `"C:\Test\test\main2.ps1 -path C:\Test\test`""

PowerShell Script

This is main0, and I have main, main1, main2.

$homepath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"

If(-NOT(Test-Path $homepath)){
    New-Item $homepath -Force | Out-Null
}

$cwd = $PSScriptRoot
Set-ItemProperty $homepath (New-Guid) '
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit "$cwd\\main.ps1" -ArgumentList "-path $cwd""
'
$name = (Get-ChildItem $cwd\*.exe | where {$_.Name -like "*exename*"}).FullName
start $name

Solution

  • Your primary problem is that you're mistakenly using a verbatim, single-quoted string ('...'):

    Therefore:

    "powershell.exe -noexit -File `"$cwd\main2.ps1`" -Path `"$cwd`""
    

    In the context of your script, using the here-string variant of an expandable string, in which case embedded " characters do not need escaping:

    # ... 
    
    $cwd = $PSScriptRoot
    Set-ItemProperty $homepath (New-Guid) @"
    C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -File "$cwd\main2.ps1" -Path "$cwd"
    "@
    
    # ...