0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ahmed
  • 86
  • 5
  • 8
    You know you don't need a batch file to run a PowerShell script, don't you? You may run `PowerShell /?` to learn how to properly call a PowerShell script. ;-) – Olaf Sep 10 '22 at 06:16
  • 2
    Running it from poweshell is better, but the requirement might be larger and form part of an existing batch-file. What exactly are your intentions. Is the scriot saved as a `.ps1` or do you want to simply run each line from batch-file? – Gerhard Sep 10 '22 at 08:11
  • This is used as *an example* in [a meta question](https://meta.stackoverflow.com/questions/420305/moderators-removing-individual-comments-which-do-not-fall-outside-of-known-guide). – Peter Mortensen Sep 10 '22 at 19:44

1 Answers1

1

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hackoo
  • 18,337
  • 3
  • 40
  • 70