Powershell script running from usb stick - privileges and arguments - windows

I'm making Powershell script that can configure pc's. I'm working with a lot of computers so script is placed on my usb stick, and I'm launching it from it. First I created 2 separated scripts, one when stick was assigned as D:\ and another when it was E:\ but it was very frustrating to make changes in both scripts, so I changed it and make it universal for every disk letter. Everything worked fine except commands were script was using built in Windows programs like netsh or cmd. Adding full path solved the problem, but Script is launching also another script when there isn't specific task in Task Register. I cannot change this second script to add there full path to programs
I've tried:
1. changing execution policy of launched script
2. changing path to script
3. changing path to powershell (full path)
bat file that launch main script:
#echo off
SET SCRIPT=path-on-usb-stick\script.ps1
SET PATH="%~dp0%SCRIPT%"
#echo on
%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -command "& %path%"
Part of the main script which cause problems:
if(!(Get-Scheduledtask | Where-Object{$_.TaskName -eq ".check-vpn-new"})) {
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command "& 'C:\...\script2.ps1' -Verb RunAs -windowstyle hidden -Wait"
}
I'm getting few errors in my output:
1. Arguments in script are null or empty but they are not
2. Script don't have access to files with administrator privileges (even if it's launched with Admin privileges)
3. script don't see Windows.old folder which should be cleaned
(everything works fine when script2 is launched from bat file)

Related

How to call PowerShell script from WSL?

In my Windows directory
C:\Users\jholmes\pichak\analytics
I have run1.ps1 code.
I run wsl.exe, now my pwd is
/mnt/c/WINDOWS/system32
How to point to the first path and execute the script?
In WSL2, using the -File option worked for me:
powershell.exe -File path/to/script.ps1
When running wsl (or wsl.exe) from PowerShell, it should start in the same directory that you were in under PowerShell, just with the Linux version of it. For instance, if you are in PowerShell in C:\Users\jholmes\pichak\analytics, and you run wsl, you should end up in /mnt/c/Users/jholmes/pichak/analytics.
If not, then you may have something in your startup file already like the other answer recommend. You should remove any cd commands from your .bashrc, .zshrc, .profile, .bash_profile, or any other startup file you may have edited.
The wsl command provides a few handy arguments for specifying the starting directory:
wsl ~ will start in your Linux user's home directory (e.g. /home/jholmes)
wsl --cd c:\ will start in /mnt/c (or whatever the equivalent Linux directory is to the Windows version passed in).
wsl --cd \\wsl$\<distroname>\etc will start in your /etc directory (or whatever WSL path you passed in. Note that you will need to specific your distribution name (obtained from wsl -l -v).
Let's say that you are in /home/jholmes, and you want to execute the PowerShell script C:\Users\jholmes\pichak\analytics\run1.ps1. You first need to translate the Windows path to the Linux version:
/mnt/c/Users/jholmes/pichak/analytics/run1.ps
You can then run it via:
powershell.exe /mnt/c/Users/jholmes/pichak/analytics/run1.ps
It's also possible to set up a PowerShell script with a "shebang" line to execute it directly. If you add the following as the first line of run1.ps1:
#!/usr/bin/env -S powershell.exe -ExecutionPolicy Bypass
Then set it to be executable via chmod +x /mnt/c/Users/jholmes/pichak/analytics/run1.ps, then it becomes a "command" of sorts (technically, an "executable script") that you can execute directly by just typing the fully qualified name of the script at the command line:
/mnt/c/Users/jholmes/pichak/analytics/run1.ps
or
cd /mnt/c/Users/jholmes/pichak/analytics
./run1.ps
There are two ways to go about this:
You can change your working directory to that of your shell script and execute it normally. To do so, follow these steps:
Mount the relevant drive cd /mnt/c/.
Change directories according to the path of the script.
This approach is more of a hack that I use for the sake of convenience. I have created a folder in my Windows storage wherein I store all Ubuntu WSL related files. Say, D:\Ubuntu. To avoid changing the working directory every time you open WSL, you can modify the shell profile file (bashrc, zshrc etc.) to load the relevant directory at the end.
i.e., Add cd /mnt/d/Ubuntu/ at the end of your ~/.zshrc file if you use zsh or the relevant profile file otherwise.
Here is the evidence, that with the WSL2, our software can make the Powershell script encrypted and protected:
See this picture:
And it can detect and kill the process that uses fanotify because we think it can be used by attackers to hide critical file change (it also can find and kill dtrace/strace/stap/bpftrace/debuggers and process that opens /dev/kmem, /dev/mem, /proc/kcore, and the protected process' /proc/pid/mem etc):
This picture shows the encrypted PowerShell script now can detect and kill possible attackers' processes
For me this answer was almost the good one but when running for instance:
powershell.exe -File /mnt/c/path/to/script/script.ps1
I got following error:
The argument '/mnt/c/path/to/script/script.ps1' to the -File parameter does not exist. Provide the path to an existing '.ps1' file as an argument to the -File parameter.
I then have to:
cd /mnt/c/path/to/script
powershell.exe -File script.ps1

Installshield - Running Powershell script from elevated command prompt

I'm using InstallShield to create an MSI that runs a .cmd file which calls a powershell script. The powershell script changes 2 registry keys. One it is removing a DENY right on a registry key for SYSTEM and the other it's changing a key's value from 0 to 1.
The script runs fine when manually executed or when I simply run the .cmd file that's used within the .MSI.
When I run the .msi, however, the cmd file runs... the powershell script executes and the value gets changed from 0 to 1... however, the DENY is not removed. The msi is running an executable custom action which I named RunCMD it is set to run in "Deferred Execution in System Context" and set to run After PublishFeatures.
I am at a loss as to why running the .cmd in this way (should be elevated) is not executing the portion of the powershell script which alters the permission on the registry key but it does allow for the value change on the other key. The script definitely runs but it partially fails when run within the .msi.
Again, if I manually run the .cmd file myself the script runs without issue so it's not a problem with the script itself.

Using RUNAS to use the local Administrator account to run a second batch file with elevated privileges

I am trying to develop a simple script that can run a second script as the machine's local administrator. As the first script I am currently trying:
set name=%computername%
runas /noprofile /user:%name%\Administrator "cmd.exe /c %cd%bg2.2.bat"
When I run the script it never seems to run the second script, which is located in the same directory. The second script is only for copying files.
del "C:\Windows\obh_logo.bmp"
copy "%cd%obh_logo.bmp C:\Windows\obh_logo.bmp"
When the first script runs I am prompted for the admin password as expected and once I enter it, a second command prompt seems to flicker on the screen then vanishes. It never appears to run the second script. What seems to be the reason for this not working?
%cd%will probably not point where you think it does, (just tested it, of course the variable gets replaced before the command gets called and does actually point to the first scripts dir, but the problem still persists in the second script)
the runaschanges the working directory for the cmd.exe instance you are starting, probably to C:\Windows\system32.
replace it with %~dp0, which yields the drive and path of the current batch file.
But! Your script will not run the second file elevated, just under the Administrator account, which is not the same. Manual confirmation is always necessary, see here for possible ways to request elevation from within your script.
I now assume the missing rights is the actual problem, add a pause statement in your second script to watch it, or call it with cmd /k so the console doesn't close.

Difference between running a command from cmd.exe or Windows Run

I'm actually trying to run an application as another user and while it works really nicely in a cmd.exe prompt, it doesn't always work if I go with the Windows Run prompt (it actually depends on what application I'm trying to run).
For example, this works fine both from cmd.exe or from W-Run prompt (using either Windows XP or Windows 7):
runas /user:ME regedit.exe
While this only works in a cmd.exe prompt (it does ask for my password in both cases but it does nothing after that if launched from W-Run on either WinXP or W7):
runas /user:ME services.msc
It's actually kind of inconsistent, with cmd it always works but with Windows Run, it's really unreliable and random.
Any ideas where there is such a difference? To get around the problem, I'm actually using batch files to launch applications as another user and then just type the batch file full path in Windows Run prompt. It does ensure reliability but I still would like to know if I'm doing something wrong.
cmd /k "runas /user:ME ""regedit.exe"" && exit"
The "problem" with runas are
It needs all the command as only one argument, so if you are running something with arguments you have to enclose all the command in quotes, and if the command includes its own quotes, they need to be escaped.
It is designed to call .exe files (well, windows valid executable files).
This two options should handle your program start
runas /user:ME "cmd.exe /c \"start services.msc\""
runas /user:ME "mmc.exe %systemroot%\system32\services.msc"
In the first case, it is using the ability of cmd.exe to find the adecuated executable to run the .msc file. In the second case, it directly calls the adecuated executable to handle the .msc file.
For your batch files, instead of cmd /k .... & exit, you can directly use cmd /c ... that will close the console when the command finishes.

How to run a PowerShell script

How do I run a PowerShell script?
I have a script named myscript.ps1
I have all the necessary frameworks installed
I set that execution policy thing
I have followed the instructions on this MSDN help page
and am trying to run it like so:
powershell.exe 'C:\my_path\yada_yada\run_import_script.ps1' (with or without --noexit)
which returns exactly nothing, except that the file name is output.
No error, no message, nothing. Oh, when I add -noexit, the same thing happens, but I remain within PowerShell and have to exit manually.
The .ps1 file is supposed to run a program and return the error level dependent on that program's output. But I'm quite sure I'm not even getting there yet.
What am I doing wrong?
Prerequisites:
You need to be able to run PowerShell as an administrator
You need to set your PowerShell execution policy to a permissive value or be able to bypass it
Steps:
Launch Windows PowerShell as an Administrator, and wait for the PS> prompt to appear
Navigate within PowerShell to the directory where the script lives:
PS> cd C:\my_path\yada_yada\ (enter)
Execute the script:
PS> .\run_import_script.ps1 (enter)
Or: you can run the PowerShell script from the Command Prompt (cmd.exe) like this:
powershell -noexit "& ""C:\my_path\yada_yada\run_import_script.ps1""" (enter)
according to Invoking a PowerShell script from cmd.exe (or Start | Run) by Kirk Munro.
Or you could even run your PowerShell script asynchronously from your C# application.
If you are on PowerShell 2.0, use PowerShell.exe's -File parameter to invoke a script from another environment, like cmd.exe. For example:
Powershell.exe -File C:\my_path\yada_yada\run_import_script.ps1
If you want to run a script without modifying the default script execution policy, you can use the bypass switch when launching Windows PowerShell.
powershell [-noexit] -executionpolicy bypass -File <Filename>
Type:
powershell -executionpolicy bypass -File .\Test.ps1
NOTE: Here Test.ps1 is the PowerShell script.
I've had the same problem, and I tried and tried... Finally I used:
powershell.exe -noexit "& 'c:\Data\ScheduledScripts\ShutdownVM.ps1'"
And put this line in a batch-file, and this works.
If you only have PowerShell 1.0, this seems to do the trick well enough:
powershell -command - < c:\mypath\myscript.ps1
It pipes the script file to the PowerShell command line.
Pretty easy. Right click the .ps1 file in Windows and in the shell menu click on Run with PowerShell.
Open PowerShell in administrator mode
Run: set-executionpolicy unrestricted
Open a regular PowerShell window and run your script.
I found this solution following the link that was given as part of the error message: About Execution Policies
Make sure to run set-ExecutionPolicy default once you're done, or you will be exposed to security risks.
Using cmd (BAT) file:
#echo off
color 1F
echo.
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "PrepareEnvironment.ps1"
:EOF
echo Waiting seconds
timeout /t 10 /nobreak > NUL
If you need run as administrator:
Make a shortcut pointed to the command prompt (I named it
Administrative Command Prompt)
Open the shortcut's properties and go to the Compatibility tab
Under the Privilege Level section, make sure the checkbox next to "Run this program as an administrator" is checked
An easy way is to use PowerShell ISE, open script, run and invoke your script, function...
In case you want to run a PowerShell script with Windows Task Scheduler, please follow the steps below:
Create a task
Set Program/Script to Powershell.exe
Set Arguments to -File "C:\xxx.ps1"
It's from another answer, How do I execute a PowerShell script automatically using Windows task scheduler?.
If your script is named with the .ps1 extension and you're in a PowerShell window, you just run ./myscript.ps1 (assuming the file is in your working directory).
This is true for me anyway on Windows 10 with PowerShell version 5.1 anyway, and I don't think I've done anything to make it possible.
Give the path of the script, that is, path setting by cmd:
$> . c:\program file\prog.ps1
Run the entry point function of PowerShell:
For example, $> add or entry_func or main
You can run from cmd like this:
type "script_path" | powershell.exe -c -
Use the -File parameter in front of the filename. The quotes make PowerShell think it is a string of commands.
I've just found the method what Microsoft do when we right click on a ps1 script and click on "Run with PowerShell" :
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & 'C:\Users\USERNAME\Desktop\MYSCRIPT.ps1'"
With the appropriate execution policy, you should just be able to call the file directly and Windows will associate it with PowerShell
C:\my_path\yada_yada\run_import_script.ps1
That does not do so well with arguments. The real answer to your question is that you are missing the & to say "execute this"
powershell.exe '& C:\my_path\yada_yada\run_import_script.ps1'

Resources