Refresh System Variable in PowerShell Script - powershell

Thank you for all the help I get here!
I researched a lot on the Internet (and StackOverFlow) but I believe there is no way I can add a System Variable within a script and somehow "restart" or "refresh" so that $env:MyTools can be populated :( I'll have to exit and request the user to restart PS.
$AddCheck = Start-Process powershell.exe -verb runAs -ArgumentList '-Command', "`"[System.Environment]::SetEnvironmentVariable('MyTools','C:\SomeFolder',[System.EnvironmentVariableTarget]::Machine)`";" -PassThru -Wait
if($AddCheck.ExitCode -eq 0)
{
Write-Host "[+] Addition Successful. Please restart PowerShell for changes to take effect!" -foregroundcolor green
""
"Exiting.."
sleep -s 5
stop-process -Id $PID
}
else
{"Something went wrong."}
Any help/inputs would be appreciated!

Related

Powershell Start-Process - notify when finished

So I am running a script to download from web and install a binary. I do that in a separate command prompt. When its done, prompt is closed. How can I know when that happened?
Example (from Windows 10) - powershell Start-Process cmd "/C tasklist"
Can I assign it to a variable and listen to some fallback function call, etc.? Like this pseudo code:
$process = powershell Start-Process cmd "/C tasklist"
while (!$process.done) {
// do stuff
}
p.s. I am very new to PowerShell. So sorry if that doesnt make sence
You could use WaitForExit()
$process = Start-Process cmd "/C tasklist" -PassThru
$process.WaitForExit()
Since you are using PowerShell, you can use background jobs for scenario:
$job = Start-Job -ScriptBlock {cmd.exe /c tasklist}
while ($job.State -eq 'Running') {
# do other stuff while waiting for job to complete
}
# To get the job results
Receive-Job $job
Based on your comments, adding -Wait makes Start-Process a synchronous command. At that point, you don't need Start-Process. You may as well just execute cmd.exe /c tasklist.

Powershell is returning exit code too quickly

I have a script to uninstall McAfee antivirus and the agent associated with it.
The issue i'm having is that the script provides an exit code too early and doesn't continue through. If I run the script multiple times I get the desired result, but as we're trying to push it out via PDQ remotely, we need it to run through the script and only provide an exit code at the end of the script.
I'm a powershell novice so there's probably a much better and easier way to write this script but any advice would be greatly appreciated.
Start-Process -FilePath "msiexec.exe" -ArgumentList "/x {CE15D1B6-19B6-4D4D-8F43-CF5D2C3356FF} REMOVE=ALL REBOOT=R /q"; Write-Host "Uninstalling McAfee VirusScan Enterprise 8.8..."
$version = (Get-WmiObject -class Win32_OperatingSystem).Caption
Write-Host "Detected OS as $version"
if ($version -like '*Windows 7*')
{
Write-Host "Uninstalling McAfee Agent..."
Start-Process -FilePath "C:\Program Files (x86)\McAfee\Common Framework\frminst.exe" -ArgumentList "/forceuninstall"
}
elseif ($version -like '*Windows 10*')
{
Write-Host "Unmanaging McAfee Agent for Uninstall Process.."
Start-Process -FilePath "C:\Program Files\McAfee\Agent\maconfig.exe" -ArgumentList "/provision /unmanaged";
Write-Host "Uninstalling McAfee Agent..."
Start-Process -FilePath "C:\Program Files\McAfee\Agent\x86\frminst.exe" -ArgumentList "/forceuninstall"
}
else
{
exit
}
Start-Process reports a return code as soon as it starts the process indicating whether it was successful or not. Either use -wait to force the script to wait until it finishes or capture the output and proceed based on what the returnvalue is. See the docs for Start-Process

Silent install of AMD driver with Powershell not working as expected?

I'm trying to make a silent install of an AMD driver with Powershell, but for some reason, I always get the AMD installation screen.
My arguments seem to be ok because I do not have to click anywhere and the installation completes by itself.Is there any way to install it without any windows popping up? I can install 7zip silently the same way without any problem.
Set-ExecutionPolicy Unrestricted
$Logpath = 'C:\powershell.log'
function Install_app
{
$exe_to_execute = 'C:\Setup.exe'
$argument = '/unattended_install:"..\Packages\Drivers\Display\W76A_INF;..\Packages\Drivers\amdkmpfd\W764a;..\Packages\Apps\ACP64;..\Packages\Apps\AppEx;..\Packages\Apps\CCC2;..\Packages\Apps\CIM;..\Packages\Apps\VC12RTx64\" /autoaccept_all /force_hide_first_run /force_close_when_done /on_reboot_message:no'
$process = Start-Process -FilePath $exe_to_execute -ArgumentList $argument -Wait -PassThru -NoNewWindow
# Loop until process exits
do {start-sleep -Milliseconds 500}
until ($process.HasExited)
# Log results
$(Get-Date).ToString() + " Exit code " + $process.ExitCode | Out-File $Logpath -Append
}
Install_app
My script is in fact actually working as it is. The problem is that it will only hide all setup windows if run under the system account.

In Powershell, do I need to use Stop-Process AND CloseMainWindow()?

I'm new to this Powershell lark, and I understood that Stop-Process should be sufficient to end a task. However, it didn't close the newly created window and it left me uncertain if the process had stopped or not.
But, after doing some ID checking, I discovered that the process ID had been removed from the list. Is it, therefore, best practice to call Stop-Process and then CloseMainWindow() ... or is CloseMainWindow() sufficient on its own?
Cls
$notepadId = Start-Process notepad -passthru
Echo "" "notepadId = "
Echo $notepadId.Id
Echo "" "Current Notepad tasks:"
Get-Process notepad
Start-Sleep -s 2
Echo "" "Stopping Task:"
Stop-Process $notepadId.Id -Force
Echo "" "Closing Window:"
(Get-Process -Id $notepadId.Id).CloseMainWindow()
Start-Sleep -s 2
Echo "" "Tasks remaining:"
Get-Process notepad
Pause
I don't know why it's not working for you, but here's how I'd write it:
Cls
$notepadProcess = Start-Process notepad -passthru
Start-Sleep -s 2
Stop-Process $notepadProcess
The return-value from Start-Process is actually a Process object, not just the ID. If you pass that process object to Stop-Process, it knows what to do. However, a few experiments suggest that Stop-Process is not synchronous, so if you do this:
Cls
$notepadProcess = Start-Process notepad -passthru
Start-Sleep -s 2
Stop-Process $notepadProcess
get-process Notepad -ErrorAction Ignore
You will probably still see the process listed, however a few hundred milliseconds sleep before the Get-Process command should be sufficent to eliminate it.

Installing AppFabric 1.1 with PowerShell DSC results in modal dialog error

I'm trying to automate the installation of AppFabric 1.1 on a Windows 2012 R2 server using PowerShell DSC. This is actually part of me trying to automate the SharePoint Foundation install and configuration, but AppFabric 1.1 is a pre-requisite. Below is a snippit from my DSC config script:
Script InstallSharePointPreRequisites
{
GetScript = { Return "InstallSharePointPreRequisites" }
TestScript = {$false}
SetScript = {
Start-Process -FilePath 'c:\temp\SharePoint\pre\MicrosoftIdentityExtensions-64.msi' -ArgumentList '/qn' -Wait | Write-verbose
Start-Process -FilePath 'c:\temp\SharePoint\pre\setup_msipc_x64.msi' -ArgumentList '/qn' -Wait | Write-verbose
Start-Process -FilePath 'c:\temp\SharePoint\pre\sqlncli.msi' -ArgumentList '/qn' -Wait | Write-verbose
Start-Process -FilePath 'c:\temp\SharePoint\pre\Synchronization.msi' -ArgumentList '/qn' -Wait | Write-verbose
Start-Process -FilePath 'c:\temp\SharePoint\pre\WcfDataServices.exe' -ArgumentList '/quiet' -Wait | Write-verbose
Start-Process -FilePath 'c:\temp\SharePoint\pre\appfabric\setup.exe' -ArgumentList '/i cacheclient","cachingService","CacheAdmin /gac /l c:\temp\appfabric.log' -Wait | Write-verbose
Start-Process -FilePath 'c:\temp\SharePoint\pre\AppFabric1.1-RTM-KB2671763-x64-ENU.exe' -ArgumentList '/quiet' -Wait | Write-verbose
}
DependsOn = "[File]GetSharePointFiles"
}
I know....the "TestScript = $false" is bad form, but I'm just trying to get the install to run at this point. :)
Anyway, when the DSC run get to the appfabric\setup.exe it's throwing the following exception:
"{"Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application."}"
When I run the Start-Process line from a normal PS prompt it installs fine and doesn't show a visible modal dialog box. I've also tried using the AppFabric setup EXE with similar switches with the same result. I'm sort of at a loss here. Has anyone else been able to install AppFabric 1.1 using PowerShell DSC? Or SharePoint Foundation 2013 for that matter? If so, how? I haven't been able to find good documentation on this scenario yet.
Thanks,
A
I solved this problem. First, there was a typo in my script. The app fabric setup line had CachAdmin rather than CacheAdmin (was missing the 'e' in cache). It took me some time and writing it a few more times to figure that out. After setting that, it is installing fine. Darn, old eyes and fat fingers... Thanks for looking. :)
A