powershell parsing special chars to cmd - powershell

I'm having trouble sending cmds from powershell 2.0 to netsh in cmd.
The wierd thing is that with one type of command to netsh it works
Example - this works:
$input1 = #"
netsh wlan connect name=Aaknet ssid=Aaknet interface="Trådløs netværksforbindelse"
"#
$OutputVariable = ($WifiOn | netsh) | Out-String
netsh runs the command without any problems, eventhough interface name contains the char å
But if I run this - Powershell parses the å as an ? to the netsh cmd
$ConnectMBN = #"
netsh mbn connect interface="Mobilbredbåndsforbindelse" connmode=name name=3
"#
$ConnectMBN | netsh
pws returns in console:
netsh>netsh>Decommand not found: netsh mbn connect interface="Mobilbredb?ndsforbindelse" connmode=name name=3.
As you can see pws turns the å into ?
Can anybody help cause I'm confused!?

Found the reason - my domain admin had redirected my %HOMESHARE% to a networkdrive
- that resultet in all the errors cause PWS couldn´t find the netsh on the share
i did this instead:
$AakHotWifiOn = #"
wlan connect name="AAKHotspot" ssid="AAKHotspot" interface="Trådløs netværksforbindelse"
"#
Invoke-WmiMethod -ComputerName . -Path win32_process -Name create -ArgumentList "netsh $AakHotWifiOn"
The same method worked with the netsh mbn cinnect issue
thanks to Graham for all the input :)

Updated based on our dialog in the comments.
The following code is an edit, of your edit, of my suggestion :-)
$Char =[Char]34
$Name ="Mobilbredbåndsforbindelse"
$Interface ="$Char$Name$Char"
$Name2="3"
$Opts = #("mbn","connect","interface=$Interface","connmode=name","name=$Name2");
netsh $Opts
So, putting the parameters for netsh into the array $Opts, using [char]34 to denote a double quote in the only parameter that needs it, interface.
Using double quotes rather than single quotes in the array items means that any variables therein are expanded so their contents are part of the parameter array.
Finally invoking netsh directly as you would on the command line, followed by the parameter array, $Opts.
As i say, i have no mobile broadband so I get error about wwansvc not running but if I enter $Opts afterwards to view the contents I see:
mbn
connect
interface="Mobilbredbåndsforbindelse"
connmode=name
name=3
EDIT: Try this (have tried using netsh wlan connect that I could test with, since I can't test mbn)...
$Char =[Char]34
$Name ="Mobilbredbåndsforbindelse"
$Interface ="$Char$Name$Char"
$Name2="3"
$connect = ("netsh mbn connect interface=$Interface connmode=name name=$Name2");
$connect

Related

Powershell DHCP scope options extraction failure using Invoke-Command

I'm trying to extract dhcp scope option info from a list of servers, the list obtained by querying AD for authorized dhcp servers in the domain. I'm using powershell's invoke-command to pass netsh dhcp server \\$servername scope $IP show optionvalue to a remote server. The $IP variable isn't passing the way the command wants to see it. It throws the The command needs a valid Scope IP Address. error.
I'm getting the scope ip address by first running netsh dhcp server \\$servername show scope and extracting the scope ip from that output, storing it in $IP.
I can type the IP in manually into the script and it returns the scope options but passing in the variable always returns the error. I've tested the command itself in a powershell console, both by manually typing in the IP and by creating a variable with the IP (as a string) and using it in the command, which works as well. There are no special characters, that i can tell, or white spaces when i store the IP in the script. I trim those out. I've also tried converting the string to an IP address using [IPAddress], to no avail.
Here is the code that gathers the scope info and then attempts to get the scope options:
foreach ($n in $name) {
$n
$showScopes = Invoke-command -computername $n -ScriptBlock {netsh dhcp server \\$n show scope}
$formatScopeInfo = $showScopes | ? {$_.Trim() -ne "" -and ($_.Contains("Disabled") -or $_.Contains("Active"))}
foreach ($en in $formatScopeInfo) {
$scopeIps = $en.Split("-")
$IP = [IPAddress]$scopeIps[0].Trim()
$IP.IPAddressToString
Invoke-Command -ComputerName $n -ScriptBlock {netsh dhcp server \\$n scope $IP.IPAddressToString show optionvalue}
}
The first foreach works and removes the lines that don't contain scope info. The second foreach partially works, it does strip out the IP. Initially i just stored it as a string, $IP = $scopeIps[0].Trim() but that wasn't working. I tried a number of things. I tried converting the octets to integers and joining them with ".", I tried to store the whole command as as a string and pass that into the Invoke-Command. Like so:
$command = "netsh dhcp server \\$n scope $IP show optionvalue"
Invoke-Command -ComputerName $n -ScriptBlock {$command}
The ultimate goal is to be able to extract any configured scope options, wherever they may be configured (server, reservation...etc). I fear I've gotten to that point where I'm so hyper-focused on what I think is the problem, that I may be missing something simple and/or crucial elsewhere. My opinion is that the command wants to see an actual IP address but my attempts to pass the variable that way have failed (and it works in the powershell console when saved as a string).
Fair disclosure, I'm still very much a novice and I was reluctant to post my code. I see so many on here with incredibly elegant solutions to things and, by comparison, my stuff seems extremely clunky. I've never had to post before as most times I can find/figure out where i've gone wrong. But I endeavor to learn and I have spent the better part of this weekend googling with no results. I have seen the script out there that works for pre 2012 servers but I really enjoy writing my own. I'm not looking to have anyone "do it for me", if you can point me down the appropriate rabbit hole; I'm happy to venture down it. Any suggestions on the code itself (appearance, better way of doing something...etc) are appreciated as well.
Apologies for the verbosity. I'm stuck and appreciate any help.
In your invoke-command you are not passing parameter,it should be like this:
$showScopes = Invoke-command -computername $n -ScriptBlock {
param($n)
netsh dhcp server \\$n show scope
} -argumentlist $n
and
Invoke-Command -ComputerName $n -ScriptBlock {
param($n,$IP)
netsh dhcp server \\$n scope $IP.IPAddressToString show optionvalue
} -argumentlist $n,$IP

Powershell: how to get rid of CMD output while assigning a variable (nslookup)

I want to run nslookup in a powershell script, assigning the output to a string variable I can parse up. I don't want to see echos like "Non-authoritative answer:" in the powershell window from the CMD execution, but everything I have tried to pipe or redirect the output of the command exclusively to the variable have not worked or broken the variable.
Example:
PS> $temp = (& nslookup 'myip.opendns.com','resolver1.opendns.com');
Non-authoritative answer:
I've tried several work-arounds...
PS> $temp = Invoke-Expression "cmd /c nslookup myip.opendns.com resolver1.opendns.com" >$null
PS> $temp = Invoke-Expression "cmd /c #ECHO off && nslookup myip.opendns.com resolver1.opendns.com"
Maybe there's a better way to do this. The way I'm working with a string here just to get the IP address is a few more lines than I'd like.
$temp = (nslookup myip.opendns.com resolver1.opendns.com) | Out-String
$temp = $temp.split()
$tempIPs = $temp -match "^(.|\r|\n)*?\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b"
$publicIP = $tempIPs[1]
return $PublicIP
I've gone this route because using two servers, like I'm doing with nslookup, doesn't seem to work with powershell's Resolve-DnsName command. I need the two servers because I'm redirecting the lookup to get my public IP. There are other ways to do that, but this one works really well and (invoke-WebRequest ifconfig.me/ip).Content has glitched out on me while working on this script.
You can specify the server to resolve your query against by specifying the -Server parameter of Resolve-DnsName.
Resolve-DnsName -Name myip.opendns.com -Server resolver1.opendns.com
From the MSDN documentation for the Resolve-DnsName command:
-Server <String[]>
Specifies the IP addresses or host names of the DNS servers to be queried. By default the interface DNS servers are queried if this parameter is not supplied.

How to get telnet output on PowerShell?

I thought I could run the command as below on PowerShell.
$output = & echo quit | telnet localhost 22
echo $output
However,
$output has nothing in it.
I'm trying to verify ssh or telnet connection.
Could you please tell me how to get output from above command ?
It is not possible. MS telnet doesn't use stdin/out. See here: C# + telnet process w/ redirected standard streams quits immediately
For redirecting the output of a telnet session you can use the -f logfile argument and then importing it into a variable after you are done with it: $output = get-contents logfile
For sending keycommands to telnet you could use $wshell = new-object -com wscript.shell and then:
start-process telnet -argumentlist "-f w:\tmp\log.txt";
sleep 1;
$wshell.SendKeys("quit{ENTER}")
Yes I know... not what you would expect, but it is the only way afaik with the MS builtin telnet console. If you know any better way, I would be glad to hear about it.
If you only want to check open ports, then why not just query them instead of telnetting? See here.
try this script and add it at start and end of your command to capture every logs
$ipV4 = (Test-Connection -ComputerName (hostname) -Count 1).IPV4Address.IPAddressToString -- this
Start-Transcript -Path .\TraceLogs_$ipV4.txt
<**Add your code here**>
Stop-Transcript
Here $ipV4 will capture the source host and logs will be generated in as file name .\TraceLogs_$ipV4.txt
Trying to adapt this for collecting Telnet output from APC PDUs (reading current load). The specified keys are successfully entered and the output is generated in the telnet session window, but the window doesn't close once the telnet session is ended. It stays open with "Connection to host lost."
I can press any key to close the window, but PS script execution does not continue, so no code following the SendKeys statement is executed.
Am I missing something simple? Code below.
$wshell = new-object -com wscript.shell
start-process telnet -argumentlist "pdu1-a6.domain.local -f c:\temptelnet.log"
sleep 1
$wshell.SendKeys("username{ENTER}password{ENTER}current{ENTER}quit{ENTER}")
$telnetoutput = get-content c:\temptelnet.log
$telnetoutput

Using netsh in powershell: save store location for multiple commands

I have a powershell script which is designed to modify the domain's ipsec policy by adding an ip address to a specified filterlist. The problem is that when running netsh store location=domain domain=our.domain.com in my powershell script, it doesn't remember the store location for following commands. I have tried a workaround by creating a text file which is then run from powershell as netsh -f "path\to\textfile.txt" but it doesn't seem to work. You will find the relevant script block below. Domain is set correctly, as it works when run directly in netsh.
$command = "ipsec static
set store location=domain domain=our.domain.com
add filter filterlist=$FILTERLIST
protocol=ANY srcaddr=$ip
srcmask=255.255.255.255
dstaddr=ME
description='IP address blocked'
mirrored=YES"
$($command.Trim()) | out-file $($DIR+"\netsh\temp.txt")
netsh -f $($DIR+"\netsh\temp.txt")
remove-item $($DIR+"\netsh\temp.txt")
I didn't get it to work yet, but as I'm about to do that, it would be nice to know if there are other better-engineered solutions for that. Im running PowerShell v.1.0
Use a here string #" ... "# with each line of your script being on separate lines in between. and pipe the command to netsh
#"
winhttp show proxy
winhttp show proxy
"# | netsh

Command/Powershell script to reset a network adapter

OS: Vista enterprise
When i switch between my home and office network, i always face issues with getting connected to the network. Almost always I have to use the diagnostic service in 'Network and sharing center' and the problem gets solved when i use the reset network adapter option.
This takes a lot of time (3-4 min) and so i was trying to find either a command or a powershell script/cmdlet which i can use directly to reset the network adapter and save myself these 5 mins every time i have to switch between the networks. Any pointers?
You can use WMI from within PowerShell to accomplish this. Assuming there is a network adapter who's device name has Wireless in it, the series of commands might look something like the following:
$adaptor = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.Name -like "*Wireless*"}
$adaptor.Disable()
$adaptor.Enable()
Remember, if you're running this with Window's Vista, you may need to run the PowerShell as Administrator.
Zitrax's answer:
netsh interface set interface "InterfaceName" DISABLED
netsh interface set interface "InterfaceName" ENABLED
was 99% of what I was looking for. The one piece of information that s/he left out, though, was that these commands have to be run as an administrator. Either run cmd.exe as an admin and type them in, or store them in a batch file, and then run that file as admin by right clicking on it and choosing "Run as Administrator" from the context menu.
See this article from The Scripting Guys, "How Can I Enable or Disable My Network Adapter?"
tl/dr:
Restart-NetAdapter -Name "Your Name Here"
You can get the list using
Get-NetAdapter
You can also try this in a .BAT or .CMD file:
ipconfig /release
ipconfig /renew
arp -d *
nbtstat -R
nbtstat -RR
ipconfig /flushdns
ipconfig /registerdns
These commands should do the same things as the 'Diagnose and Repair' for the network adapter, but is WAY faster!
Let me know if this helps!
JFV
What worked for me:
netsh interface show interface
to show the interface name which for me was "Ethernet 2" and then:
netsh interface set interface "Ethernet 2" DISABLED
netsh interface set interface "Ethernet 2" ENABLED
The following command worked for me (on Server 2012 R2):
Restart-NetAdapter -Name "Ethernet 2"
Replace "Ethernet 2" with the name of your adapter.
Note: To create a PS script: create a new document in Notepad, save is as script.PS1, insert the line above and save. Right click the file -> Run with PowerShell.
For more see this technet article.
The post of Scott inspired me to write a very small C# / .Net console application, that uses System.Management. You can name the adapter, that you want to restart, as a command line parameter. The code shows some basics about handling devices, that could be useful for others too.
using System;
using System.Management;
namespace ResetNetworkAdapter
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("ResetNetworkAdapter [adapter name]");
Console.WriteLine("disables and re-enables (restarts) network adapters containing [adapter name] in their name");
return;
}
// commandline parameter is a string to be contained in the searched network adapter name
string AdapterNameLike = args[0];
// get network adapter node
SelectQuery query = new SelectQuery("Win32_NetworkAdapter");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection adapters = searcher.Get();
// enumerate all network adapters
foreach (ManagementObject adapter in adapters)
{
// find the matching adapter
string Name = (string)adapter.Properties["Name"].Value;
if (Name.ToLower().Contains(AdapterNameLike.ToLower()))
{
// disable and re-enable the adapter
adapter.InvokeMethod("Disable", null);
adapter.InvokeMethod("Enable", null);
}
}
}
}
}
This is what I use on PowerShell version 5.0.10586.122 Windows 10 Home. This needs to be run as an administrator:
Restart-NetAdapter -Name "ethernet"
To run this as an administrator without having to "Turn off UAC" or "R-Click-> Run as administrator": (This is a one time task)
Put the above Restart-NetAdapter -Name "ethernet" into a .ps1 file
Create a new shortcut (R-Click on .ps1 file > Create Shortcut)
On the Shortcut, R-Click > Properties > Shortcut > Target > (Append Powershell.exe to precede the Location/filename as shown below.
Also enclose the Location/filename with double quotes("), also shown below.
On the Shortcut, R-Click > Properties > Shortcut > Advanced > "Run As Administrator"(Check this Check box)
Now every time you run the shortcut, you will need to just click "Yes" on the UAC screen and it will reset the adapter you've specified in the .ps1 file.
To get the names of the available adapters using PowerShell(WiFi, LAN etc.,):
Get-NetAdapter
You can also use the Microsoft utility devcon.exe.
First, run devcon listclass net to find your Device ID.
Then use this device ID in this command: devcon restart PCI\VEN_16* (using the '*' wildcard to avoid needing to enter the entire ID string).
You can also restart a NIC using wmic command:
Get interface ID:
C:\>wmic nic get name, index
Disable NIC (InterfaceID:1):
wmic path win32_networkadapter where index=1 call disable
Enable NIC (InterfaceID:1):
wmic path win32_networkadapter where index=1 call enable
Source: http://www.sysadmit.com/2016/04/windows-reiniciar-red.html
You could also try netsh commands. Example:
netsh wlan disconnect && netsh wlan connect [ONE OF YOUR WLAN PROFILES]
You can get a list of those "profiles", using:
netsh wlan show profiles
ipconfig /flushdns
ipconfig /renew
Are the 2 cmdlets I use to refresh my connection. You don't necessarily need to power cycle the router to re-gain a strong signal( I know power cycling clears the router's memory but that's really it).
Thanks for the Info that it can be done with netsh.
I wrote a simple "Repair.bat" script:
#echo off
netsh interface set interface "%1" DISABLED
netsh interface set interface "%1" ENABLED
Just call it with the name of the NIC, renamed as i.e. "WLAN" so I does not have spaces, type "Repair WLAN" into cmd does the trick.
I'll place it into system32 and make a task of it or see how to integrate it into the network context menu...