How can I run this PowerShell script in a batch file? [duplicate] - powershell

This question already has answers here:
How do I have to change PowerShell variables code so that I can run it via CMD?
(4 answers)
Closed 5 months ago.
How can I run this PowerShell script in a batch file?
(netsh wlan show profiles) | Select-String "\:(.+)$" |
%{$name=$_.Matches.Groups[1].Value.Trim(); $_} |
%{(netsh wlan show profile name="$name" key=clear)} |
Select-String "Key Content\W+\:(.+)$" |
%{$pass=$_.Matches.Groups[1].Value.Trim(); $_} |
%{[PSCustomObject]#{ PROFILE_NAME=$name;PASSWORD=$pass }} |
Format-Table -AutoSize >> "Wifi.txt"
I found some solutions, but I couldn't find a regular way, so I couldn't solve this problem.
I want to run all PowerShell lines in one line in a batch file, like powershell.exe -command....., but I don't know how to put the sentence like this.

PowerShell in One line
netsh wlan show profiles|SLS "\:(.+)$"|%{$SSID=$_.Matches.Groups[1].Value.Trim(); $_}|%{(netsh wlan show profile name="$SSID" key=clear)}|SLS "Conte.*:(.+)$"|%{$pass=$_.Matches.Groups[1].Value.Trim(); $_}|%{[PSCustomObject]#{SSID=$SSID;PASSWORD=$pass}}
With a hybrid batch file / PowerShell:
<# : batch script
#rem # The previous line does nothing in Batch, but begins a multiline comment block in PowerShell. This allows a single script to be executed by both interpreters.
#echo off
Title Wifi Passwords Recovery
setlocal
cd "%~dp0"
Color 0B & echo(
Echo( Please Wait a while ... Executing the PowerShell command ...
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
If Exist WifiKeys.txt Start /MAX "" WifiKeys.txt
EndLocal
goto:eof
#>
# Here write your PowerShell commands...
netsh wlan show profiles|SLS "\:(.+)$"|%{$SSID=$_.Matches.Groups[1].Value.Trim(); $_}|%{(netsh wlan show profile name="$SSID" key=clear)}|SLS "Conte.*:(.+)$"|%{$pass=$_.Matches.Groups[1].Value.Trim(); $_}|%{[PSCustomObject]#{SSID=$SSID;PASSWORD=$pass}}>WifiKeys.txt

Related

CMD to PowerShell converter

Does anyone know how to convert this CMD script to PowerShell script?
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge\ExtensionInstallBlocklist" /v 1 /t REG_SZ /d *
I have tried saving it as ps1 file, the weird thing is that it works when I run it in PowerShell terminal but when I save it as a powershell file and try to run it I get an error.
EDIT:
PowerShell script files were disabled due to security reasons but I've enabled it now, I am using Windows 11 and would need to run that file as an admin but can't find a way to do it.
Thanks
This is the equivalent command in pure Powershell. This will need to be run from an elevated Powershell prompt
New-Item "HKLM:SOFTWARE\Policies\Microsoft\Edge\ExtensionInstallBlocklist" | New-ItemProperty -Name 1 -Value * -PropertyType String

Removal of Office

I'm currently trying to run a batch file as a startup script to detect and remove whatever version of office a user has installed and then to install Office 365. I have the install working however, when I attempted to uninstall Office 2013 I received the following error:
Input Error: Can not find script file "C:\Windows\OffScrub_O15msi.vbs"
The Offscrub file is in the same location as the script, is someone able to tell me why it's looking in C:\Windows for it?
Update
Please find my current script which now works for Office 2013, I previously added the line Remove2016Installs $true when using -Command to remove Office 2016, this worked. Since using -File to work around my initial problem I've been unable to get the script to remove Office 2016 and would like some advice on how to do this, I've read that whatever command is after -File needs to be the last which I believe might be why it's failing.
My full script is below:
start "----NOTICE----" cmd.exe /t:ec /Q /k "echo OFFICE 365 IS BEING INSTALLED. THIS WINDOW WILL CLOSE WHEN COMPLETE&&prompt $h"
#echo off
pushd "%~dp0"
powershell.exe -executionpolicy bypass -NoExit -File "Remove-PreviousOfficeInstalls.ps1"
popd
reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" | find /i "x86" > NUL && set OS=32BIT || set OS=64BIT
if %OS%==32BIT "\\domain\SYSVOL\domain\Policies\{Policy Number}\Machine\Scripts\Startup\setup.exe" /configure "\\domain\SYSVOL\domain\Policies\{Policy Number}\Machine\Scripts\Startup\configuration-Office365-x86.xml"
if %OS%==64BIT "\\domain\SYSVOL\domain\Policies\{Policy Number}\Machine\Scripts\Startup\setup.exe" /configure "\\domain\SYSVOL\domain\Policies\{Policy Number}\Machine\Scripts\Startup\configuration-Office365-x64.xml"
taskkill /IM cmd.exe /FI "WINDOWTITLE EQ ----NOTICE----"
taskkill /IM cmd.exe /FI "WINDOWTITLE EQ Administrator: ----NOTICE----"
echo %date% %time% Setup ended with error code %errorlevel%. >> %LogLocation%\%computername%.txt
Update Finished
There's a line that calls the Powershell script Remove-PreviousOfficeInstalls, this is a file from GitHub that is very popular for the removal of whichever Office version you have installed.
I can run this command if say I copy these files to the desktop and amend the locations in the scripts, I'm not sure what this reference to C:\Windows is though when run from \domain\SYSVOL\domain\Policies{Policy Number}\Machine\Scripts\Startup\?
If you run a default instances of PowerShell it always starts in a certain directory. It depends on how and who it is started by. For instance an administrative PowerShell usually starts in C:\Windows\System32. If you use any paths that are not absolute they're applied relative to this directory.
To work around this you need to change the directory it's using. For instance by using cd to change the directory. My guess would be that your script Remove-PreviousOfficeInstalls.ps1 contains a relative call to the VBS.
An easy fix would be to run a script block instead of a single command and just cd to \\domain\SYSVOL\domain\Policies\'{Policy Number}'\Machine\Scripts\Startup\ prior to running the ps1.
The PowerShell help you can view by following [this] link or running powershell -h has the following information in regards to using the -Command switch.
...
Script blocks must be enclosed in braces ({}). You can specify a script block only when running PowerShell.exe in PowerShell. If you want to use a script block when running from another shell you must use the format:
"& {}"
...
The other important parameter for your use case is -File.
Runs the specified script in the local scope ("dot-sourced"), so that the functions and variables that the script creates are available in the current session. Enter the script file path and any parameters.
...
Your batch contains the following line:
powershell.exe -executionpolicy bypass -Command "\\domain\SYSVOL\domain\Policies\'{Policy Number}'\Machine\Scripts\Startup\Remove-PreviousOfficeInstalls.ps1 -Remove2016Installs $true"
What you do is run a single command to invoke a script with a parameter. The problems is that said script checks its locations based on certain function and with your invocation that location is wrongly detected.
There are multiple ways to fix this. One would be to change the directory before invoking the script. To do this you'd need to use a script block as the parameter for -Command. An example for this would be:
powershell.exe -Command "& {Write-Output 'Hello'; Write-Output 'World';}"
As you can see there are two independent Write-Output commands being run. You'd change this to a cd \\domain\SYSVOL\domain\Policies\'{Policy Number}'\Machine\Scripts\Startup\ and the invocation of your script. As a bonus you wouldn't need to put the whole path in front of the script anymore.
The other option would be to run powershell -File with your current invocation of the script. That should also mean that the script is read from the file and the corresponding parameters are populated accordingly.
If neither of these options work you will have to check what $PSScriptRoot is being populated with and/or what the return of (Get-Item -Path ".\").FullName is as those are the two commands used to determine the location of the script that's being executed. To do this you could use a script block.
thanks for your help regarding this. My resolution was to use the following bat command:
`start "----NOTICE----" cmd.exe /t:ec /Q /k "echo OFFICE 365 IS BEING INSTALLED. THIS WINDOW WILL CLOSE WHEN COMPLETE&&prompt $h"`
#echo off
pushd "%~dp0"
powershell.exe -executionpolicy bypass -File Remove-PreviousOfficeInstalls.ps1 -Remove2016Installs
popd
reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" | find /i "x86" > NUL && set OS=32BIT || set OS=64BIT
if %OS%==32BIT "\\Server\Folder\Folder\setup.exe" /configure "\\Server\Folder\Folder\configuration-Office365-x86.xml"
if %OS%==64BIT "\\Server\Folder\Folder\setup.exe" /configure "\\Server\Folder\Folder\configuration-Office365-x64.xml"
taskkill /IM cmd.exe /FI "WINDOWTITLE EQ ----NOTICE----"
taskkill /IM cmd.exe /FI "WINDOWTITLE EQ Administrator: ----NOTICE----"
echo %date% %time% Setup ended with error code %errorlevel%. >> %LogLocation%\%computername%.txt
I had to amend the Remove-PreviousOfficeInstalls powershell script to include the switch command:
[Parameter(ValueFromPipelineByPropertyName=$true)]
[switch]$Remove2016Installs = $false,
This then did exactly what I was after, it detected the current version of Office, removed it and installed the correct bit version of Office 365 for that PC\Laptop.
Thanks for all your help

how do I make it easy for my parents to run this Powershell command?

I am not a programmer and my parents' Windows 10 PC tends to loose its start menu and cortana processes, resulting in start menu not showing up at all when the start icon is clicked.
I made a quick search and found + tested this Powershell command and it worked:
Get-AppxPackage | % { Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppxManifest.xml" -verbose }
I wish to turn this command into a shortcut/batchfile that executes the command and restarts the PC whenever the desktop icon is double clicked, in order to avoid explaining to my parents what to do to fix the problem. Can any one help me out please?
Thank you in Advance.
you can encode the command and put the whole thing into a single batch file (no .ps1 necessary)
details here
https://blogs.msdn.microsoft.com/timid/2014/03/26/powershell-encodedcommand-and-round-trips/
or you can use this function
https://github.com/gangstanthony/PowerShell/blob/master/Encode-Text.ps1
first, either use Get-Content or Get-Clipboard (copy your whole script to the clipboard) to encode your desired script
PS> Encode-Text (Get-Clipboard | out-string)
RwBlAHQALQBBAHAAcAB4AFAAYQBjAGsAYQBnAGUAIAB8ACAAJQAgAHsAIABBAGQAZAAtAEEAcABwAHgAUABhAGMAawBhAGcAZQAgAC0ARABpAHMAYQBiAGwAZQBEAGUAdgBlAGwAbwBwAG0AZQBuAHQATQBvAGQAZQAgAC0AUgBlAGcAaQBzAHQAZQByACAAIgAkACgAJABfAC4ASQBuAHMAdABhAGwAbABMAG8AYwBhAHQAaQBvAG4AKQBcAEEAcABwAHgATQBhAG4AaQBmAGUAcwB0AC4AeABtAGwAIgAgAC0AdgBlAHIAYgBvAHMAZQAgAH0ADQAKAA==
then you can use that in your batch file like so
powershell -encodedcommand RwBlAHQALQBBAHAAcAB4AFAAYQBjAGsAYQBnAGUAIAB8ACAAJQAgAHsAIABBAGQAZAAtAEEAcABwAHgAUABhAGMAawBhAGcAZQAgAC0ARABpAHMAYQBiAGwAZQBEAGUAdgBlAGwAbwBwAG0AZQBuAHQATQBvAGQAZQAgAC0AUgBlAGcAaQBzAHQAZQByACAAIgAkACgAJABfAC4ASQBuAHMAdABhAGwAbABMAG8AYwBhAHQAaQBvAG4AKQBcAEEAcABwAHgATQBhAG4AaQBmAGUAcwB0AC4AeABtAGwAIgAgAC0AdgBlAHIAYgBvAHMAZQAgAH0ADQAKAA==
You could execute the PowerShell script via a batch file.
Batch file:
set powerscriptPath=C:\Example.ps1
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%powerscriptPath%""' -Verb RunAs}"
This will bypass the execution policies on the computer allowing the script to run in Administrator mode too. NOTE: You will need to edit the powerscriptPath to point to your PowerShell script location, I just used C:\Example.ps1 as an example.
You will want to add Restart-Computer -Force to the end of your PowerShell script to restart the computer
Get-AppxPackage | % { Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppxManifest.xml" -verbose }
Restart-Computer -Force
Make a bat file which executes powershell with that file. Then add a shortcut to the bat file
I am really unsure why you would run a batch file just to call a powershell script! Talk about hokey approaches to a non-problem.
To call a powershell script is really no different than calling a batch script:
It's simply path to PowerShell, and the script path as a parameter:
"%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" "C:\users\austinfrench\desktop\example.ps1"
You can also use the exact same format as the target for a desktop shortcut.

Openfiles query to see open files

How can I call the Openfiles.exe (which is on the server 2008 file server) remotely from a computer to see which files are open by the users? I also need to have it login as the domain admin user in the parameters.
Openfiles can do a server direct. You don't have to run it remotely.
From Help openfiles /query /?
OPENFILES /Query /S system /U username /P password /NH
A way to do it in PowerShell and to allow for searching would be with this small function.
function Get-OpenFiles {
cls
openfiles /query /s $args[0] /fo csv /V | Out-File -Force C:\temp\openfiles.csv
$search = $args[1]
Import-CSV C:\temp\openfiles.csv | Select "Accessed By", "Open Mode", "Open File (Path\executable)" | Where-Object {$_."Open File (Path\executable)" -match $search} | format-table -auto
Remove-Item C:\temp\openfiles.csv
}
It allows you to call Get-OpenFiles Server Filename and it will show you the results. The caveat is that you have a folder called C:\temp.
So if I do Get-OpenFiles TestServer Hardware I get the below.
Accessed By Open Mode Open File (Path\executable)
----------- --------- ---------------------------
NFDJWILL Read N:\Network Services\Documentation\Hardware.xlsx
NFDJWILL Write + Read N:\Network Services\Documentation\Hardware.xlsx
NFDJWILL Read N:\Network Services\Documentation\Hardware.xlsx
Here is a solution without creating temporary files.
function Get-OpenFile
{
Param
(
[string]$ComputerName
)
$openfiles = openfiles.exe /query /s $computerName /fo csv /V
$openfiles | ForEach-Object {
$line = $_
if ($line -match '","')
{
$line
}
} | ConvertFrom-Csv
}
Get-OpenFile -ComputerName server1
You can now do this with the PowerShell command Get-SmbOpenFile.
how to run application remotely by using Power Shell
https://technet.microsoft.com/en-us/library/dd819505.aspx
your PS or BAT script will be:
openfiles.exe > c:\temp\openfiles.txt
of course better use different output folder and file name.
Alternative way:
https://technet.microsoft.com/en-ca/sysinternals/bb897553.aspx -- PsExec -- PsExec is a light-weight telnet-replacement that lets you execute processes on other systems, complete with full interactivity for console applications, without having to manually install client software.
You can use a remote delegated powershell session for this.
Use Delegated Administration and Proxy Functions
You can delegate the admin credentials in RunAs setting of the session configuration, and constrain the session to only being able to run the openfiles.exe. Then you can assign permission to use to session to selected groups or users. This enables you to let people run cmdlets or programs that require domain admin authority, without giving them the domain admin credentials.
No need to create a CSV file and have to remove it later, or be concerned about its' size.
openfiles /s MyFileSrv /query /fo CSV /v /u admin1 /p myPass | convertfrom-csv |?{$_.'Open File (Path\executable)' -match "MyFolder"} |select 'Accessed By', 'Open Mode', 'Open File (Path\executable)
Accessed By Open Mode Open File (Path\executable)
----------- --------- ---------------------------
robinsonl Write + Read D:\Dept\MyFolder
smithd Read D:\Dept\MyFolder\info
If you're using powershell 1.0 then add |select -skip 8| before the convertfrom-csv portion.

curl http://url/script.ps1 | powershell possible?

I just want to replicate the same behavior that I do on Linux systems
c:\> \{CURL_EQUIVALENT_ON_WINDOWS} - http://url/script | powershell
Is that possible?
Basically I want to execute a stream I download from a server.
IE: in steps:
1) Find out how to execute streams in a powershell.
Execute a stream (that I already have on the file system)
c:\> type script.ps1 | powershell -command -
but this doesn't work.
There is an option -File to execute a "File", and basically I want to execute the stream if possible.
2) Find out how to execute a stream I download from the server and pipe it in to a powershell.
Thanks to dugas I learn how to execute streams with powershell, and with this link http://blog.commandlinekungfu.com/2009/11/episode-70-tangled-web.html I understand how to get content as a stream from http with powershell.
So the final curl | powershell pipe looks like this:
PS C:\>(New-Object System.Net.WebClient).DownloadString("http://url/script.ps1") | powershell -command -
Thanks a lot to everyone that contribute to this question :-)
You can specify the command parameter of powershell with a hyphen to make it read its command from standard input. Below is an example:
"Write-Host This is a test" | powershell -command -
Example of using contents of a script file:
Get-Content .\test.ps1 | powershell -command -
From the powershell help menu:
powershell /?
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
If the value of Command is "-", the command text is read from standard
input.