In powershell i can download a script in a specific random name created folder but i cannot find the right way to execute the script from there.Here the code that i used:
$uuid=(Get-WmiObject Win32_ComputerSystemProduct).UUID;
$path = $env:appdata+'\'+$uuid; $h=$path+'\d';
if(!(test-path $path)) { New-Item -ItemType Directory -Force -Path
$path;};
Invoke-WebRequest mywebsitefordownloadingscript -OutFile $path\\test.txt;
start-process -Windowstyle hidden cmd '/C
'powershell.exe' -exec bypass $path\\test.txt';
there was something missing in last string maybe the problem persist if i use '+$path+' too.
Any suggestions??
The problem is your single quotes on the last two lines. Since you have enclosed $path within single quotes it is not expanded and is taken literally. Change to double quotes to expand the variable, and this should work.
$uuid=(Get-WmiObject Win32_ComputerSystemProduct).UUID
$path = $env:appdata+'\'+$uuid
$h=$path+'\d'
if(!(test-path $path)) {
New-Item -ItemType Directory -Force -Path $path
}
Invoke-WebRequest mywebsitefordownloadingscript -OutFile $path\\test.txt
start-process -Windowstyle hidden cmd "/C 'powershell.exe' -exec bypass $path\\test.txt"
Related
I have to find and then execute a .exe file from a script deployed by our asset management software. Currently it looks like this:
Set-Location $PSScriptRoot
$proc = (Start-Process -FilePath "C:\Program Files (x86)\software\software name\Uninstall.exe" -ArgumentList "/S /qn" -Wait -PassThru)
$proc.WaitForExit()
$ExitCode = $proc.ExitCode
Exit($ExitCode)
As far as I understand the location for the location for the file is set and some users do not have it there hence why it fails.
So I understand that you can search for a program with
Get-ChildItem C:\Program Files (x86)\software\
And execute with Start-process -Filepath
But do I simply combine that with a | or is there an easier way/will it even work.
As commenter suggested, you can use Test-Path to test if a path exists:
$uninstallPath = Join-Path ${env:ProgramFiles(x86)} 'software\software name\Uninstall.exe'
if( Test-Path $uninstallPath ) {
$proc = Start-Process -FilePath $uninstallPath -ArgumentList '/S /qn' -Wait -PassThru
$proc.WaitForExit()
$ExitCode = $proc.ExitCode
Exit $ExitCode
}
I've also made the code more robust by avoiding the hardcoded "Program Files (x86)" directory, using an environment variable. Because of the parentheses in the name of the env var, it must be enclosed in curly braces.
For added robustness, you may read the path of the uninstall program from the registry, as detailed by this Q&A. If you are lucky, the program even stores a QuietUninstallString in the registry, which gives you the full command line for silent uninstall.
I am trying to run script to manage some VHD Disks, but the disk mount is failing due to elevated permissions required. The user the script is run under is a local admin, but UAC is blocking it I think. The error which comes back is: “DiskState=Failed to mount disk - "Access to a CIM resource was not available to the client”
Ideally I need to the script to run under elevated command prompt automatically. Any idea's how I can achieve that programmatically?
The script I am running is this:
$location = "C:\temp"
$name = "downloadfile"
$Author = "FSLogix"
$FilePath = "Filepath here"
$LogFilePath = "Logfilepath here"
# Force to create a zip file
$ZipFile = "$location\$Name.zip"
New-Item $ZipFile -ItemType File -Force
$RepositoryZipUrl = "https://github.com/FSLogix/Invoke-FslShrinkDisk/archive/master.zip"
# download the zip
Write-Host 'Starting downloading the GitHub Repository'
Invoke-RestMethod -Uri $RepositoryZipUrl -OutFile $ZipFile
Write-Host 'Download finished'
#Extract Zip File
Write-Host 'Starting unzipping the GitHub Repository locally'
Expand-Archive -Path $ZipFile -DestinationPath $location -Force
Write-Host 'Unzip finished'
# remove the zip file
Remove-Item -Path $ZipFile -Force
# Run the FSLogix Optimisation
C:\temp\Invoke-FslShrinkDisk-master\Invoke-FslShrinkDisk.ps1 -Path $FilePath -Recurse -PassThru -LogFilePath $LogFilePath\logfile.csv
You can elevate the PS script using the Powershell as a separate process and make it "run as admin" like below:
start-process PowerShell -verb runas
OR
Powershell -Command "Start-Process PowerShell -Verb RunAs"
Apart from that , you can condition it as well. There is a beautiful conditional code shared by PGK which can help as well:
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" +$myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
I have a ps1 file in Onedrive for Business path. when running below command, it gets something wrong, but it runs so fast, I can't get the error screenshots.
If I put the script in another local drive path, it works fine.
Any prevention in Onedrive?
Start-Process powershell.exe -ArgumentList $ps1path
ps file content
$current_path = Split-Path -Parent $MyInvocation.MyCommand.Definition
$up1_path = Split-Path -Parent $current_path
$up2_path = Split-Path -Parent $up1_path
$up1_path
$up2_path
cmd /c "pause"
It's not Onedrive case. Just the start-process can't accept a space in ArgumentList.
$pspath = $pspath -replace ' ','` '
Start-Process powershell.exe -ArgumentList $pspath
I have a series of ps1 files in a directory, all of which have different names. I am trying to run them one after another with Start-Process and the -Wait parameter. How does loop through all the files in a directory and run one PowerShell script after another? There are no subfolders, and no files that are not of type ps1.
Here is my start:
$DirectoryList = Get-Content -Path C:\test
foreach ($Directory in $DirectoryList) {
Start-Process -FilePath powershell.exe -ArgumentList ('"{0}\How To Read Me.ps1" -Path "{1}"' -f $PSScriptRoot, $Directory);
}
You could simply use the call operator (&):
Get-ChildItem 'C:\test' | ForEach-Object {
& $_.FullName
}
I am trying to create a context menu but once its created i get an error message stating
This file does not have a program associated to it.
i am using this script . I am trying to create a powershell shortcut on folders.
New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
Test-Path HKCR:\Directory\shell\Powershell
New-Item -Path HKCR:\Directory\shell -Name Powershell
Set-Item -Path HKCR:\Directory\shell\Powershell -Value "Open Powershell Here"
New-Item -Path HKCR:\Directory\shell\Powershell\key -Value
"C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -NoExit -Command Set-Location -
LiteralPath '%L'"
Try to change last line:
New-Item -Path HKCR:\Directory\shell\Powershell\key -Value "C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -NoExit -Command ""Set-Location -LiteralPath '%L'"""
If not work add a third '"' """Set-location...