Powershell Get-NetAdapterAdvancedProperty - windows

I am trying to run Powershell command from batch file test.bat. I am actually calling this command from Python Popen not from test.bat.(I am using test.bat just for validation)
powershell.exe (Get-NetAdapterAdvancedProperty -Name "SLOT 1" -DisplayName "Jumbo Packet").DisplayValue
Same command works with out second argument -DisplayName "Jumbo Packet" from python and batch
Error I get when I use second argument is below:
Get-NetAdapterAdvancedProperty : A positional parameter cannot be
found that accepts argument '1'. At line:1 char:2
+ (Get-NetAdapterAdvancedProperty -Name SLOT 1 -DisplayName:Jumbo Packet).DisplayV ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-NetAdapterAdvancedProp erty], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Get-NetAdapterAdvanc edProperty
*
But if I run the same command from Powershell window I get my expected result.
(Get-NetAdapterAdvancedProperty -Name "SLOT 1" -DisplayName "Jumbo Packet").DisplayValue
I am new to Powershell.Thanks for your help
Python code:
iface="SLOT 1"
cmd= 'powershell.exe (Get-NetAdapterAdvancedProperty -Name "'+ iface +'" -DisplayName "Jumbo Packet").DisplayValue'
conn.modules.os.popen(cmd).read()

Brackets have special meaning in command. Escape them with a caret. The quotes may also need escaping with a caret.
But why the indirection. PS uses WMI. WMI is also available via COM. Python can do COM.
This is VBScript pulling out nics. You should be able to do this in any language that supports COM (nearly all).
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_NetworkAdaptor")
For Each objItem in colItems
msgbox objitem.name
Next

Put double quotes around the whole command string (to make the entire command a string for CMD). Use single quotes inside the double-quoted string to define the nested strings for PowerShell:
powershell.exe "Get-NetAdapterAdvancedProperty -Name 'SLOT 1' -DisplayName 'Jumbo Packet').DisplayValue"
Alternatively escape nested double quotes with backslashes:
powershell.exe "Get-NetAdapterAdvancedProperty -Name \"SLOT 1\" -DisplayName \"Jumbo Packet\").DisplayValue"
However, in general it's less troublesome to simply put PowerShell commands in a script and run that script with PowerShell:
powershell.exe -File "C:\path\to\your.ps1"

Related

Use PowerShell to create a shortcut to launch a PowerShell script

I have a need to create a shortcut on a Windows 2019 Server for the Eclipse application so that it runs a PowerShell script instead of opening Eclipse. The script runs a few commands first and then opens the Eclipse application. When I edit an existing shortcut for Eclipse, I can modify the target to be:
"powershell.exe -ExecutionPolicy bypass C:\temp\eclipse-fix.ps1 -WindowStyle Hidden"
This works fine when completed manually. However, when I try to do the same with a PowerShell script, to automate the process, I get an error.
Contents of the script:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("C:\Users\Administrator\Desktop\Eclipse.lnk")
$Shortcut.TargetPath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy bypass C:\cfn\temp\eclipse-fix.ps1 -WindowStyle Hidden"
$Shortcut.IconLocation = "%SystemDrive%\eclipse\eclipse.exe"
$Shortcut.Save()
Error Returned:
PS C:\Users\Administrator> $WshShell = New-Object -comObject WScript.Shell
PS C:\Users\Administrator> $Shortcut = $WshShell.CreateShortcut("C:\Users\Administrator\Desktop\Eclipse.lnk")
PS C:\Users\Administrator> $Shortcut.TargetPath = "powershell.exe -File C:\cfn\temp\eclipse-fix.ps1"
Value does not fall within the expected range.
At line:1 char:1
+ $Shortcut.TargetPath = "powershell.exe -File C:\cfn\temp\eclipse-fix. ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
PS C:\Users\Administrator> $Shortcut.IconLocation="%SystemDrive%\eclipse\eclipse.exe, 0"
PS C:\Users\Administrator> $Shortcut.Save()
Result:
The icon is created but has no value for target.
Does anyone know what I am missing to get this to work? Is there another option to use that I may not be aware of?
Thanks.
You need to specify the Arguments separate from the TargetPath
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("C:\Users\Administrator\Desktop\Eclipse.lnk")
$Shortcut.TargetPath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
$Shortcut.Arguments = "-ExecutionPolicy bypass C:\cfn\temp\eclipse-fix.ps1 -WindowStyle Hidden"
$Shortcut.IconLocation = "%SystemDrive%\eclipse\eclipse.exe"
$Shortcut.Save()
You can also use just powershell.exe in place of the full path. Either will work.
Here is a script I wrote that will create a shortcut to itself on the desktop that is executable (Can run by double clicking) when run.
I did this to take the step-by-step process out of colleagues having to create their own shortcuts of my powershell automation scripts.
Because our shared drive at work is a different location for everybody, I use the "Get-location" command which gets the pwd, then trim it and parse it for use within the shortcut's argument field.
In order to have the arguments contain double quotes, you have to use the escape character ` preceding another set of quotes, this will allow for the script to send quotes to the arguments field. It will not work without this. '" '"
Make sure that when you are running the script you are not running it from the powershell IDE, or the file paths will be wrong. You need to save the script in your target source path and the nrun it from there by either right ckicling it and running it as a powershell script or creating an executable shortcut for it. Let me know if you need instructions on how to create an executable powershell shortcut.
Hope this helps!
#Grap the pwd
$location = Get-Location | Select Path | ft -HideTableHeaders | Out-String;
#Trim the pwd variable of any extra spaces and unwanted characters
$location = $location.Trim();
$locations = $location.replace(' ' , '');
$locations = $locations.replace("`n","");
#Make the source file location my path to powershell.exe
$SourceFileLocation = "`"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`"";
# Declare where I want to place the shortcut, I placed it on the desktop of whomever is running the script with the dynamic $env:USERNAME which takes the username of whomever is running the script - You can name the shortcut anything you want at the end as long as it ends with .LNK
$ShortcutLocation = “C:\Users\$env:USERNAME\OneDrive\Desktop\PopupSortcut.lnk”;
#Create a now com
$WScriptShell = New-Object -ComObject WScript.Shell;
#create shortcut and provide the location parameter as an argument
$Shortcut = $WScriptShell.CreateShortcut($ShortcutLocation);
#set the target path
$Shortcut.TargetPath = $SourceFileLocation;
#Add arguments that will bypass the execution policy as well as provide a path to the source powershell script (make sure that the entire argument has double quotes around it and that the internal quotes have escape characters (`) behind them, these are not apostrophes but back ticks, located on the same key as the tilde (~) key on the keyboard
$Shortcut.Arguments = “-ExecutionPolicy Bypass -file `"$locations"+"Pop-up.ps1`"”;
#Save the Shortcut
$Shortcut.Save();
########################### This is the meat of our script Performing an Operation #######################
$wshell = New-Object -ComObject Wscript.Shell;
$wshell.Popup("Operation Completed",0,"Done",0x1);

Using ruby variable in a PowerShell script with winrm

EDIT:
I would like to count files/folders of storage containers via virtual machine manager PowerShell cmdlet.
I went over similar questions, but still am struggling with syntax.
I have a ruby script that is executing a PowerShell script on a remote server.
I want to use a ruby variable within the Powershel script.
For example
path_str = "\\XXX\YYY\" #This is the ruby var
PSoutput = shell.run(" #This part is executing the PS script
$Files = Get-ChildItem -Recurse -File -Path #{path_str} | Measure-Object | %{$_.Count}" | stdout
How do I use the ruby variable path_str with the PS script?
I have tried
# {path_str}
\" " + path_str + " \"
Double quotes and single quotes
Nothing worked for me.
There are a few things that I see causing the issues.
# is a reserved character in powershell. When you use #, anything after that is a comment.
You are assigning the output of Get-ChildItem to $files. There will be no output from shell.run() to assign to PSoutput because output from cmdlet is getting assigned to $files.
Get-ChildItem is a powershell specific command, not a command line / dos command that you can execute from within shell, without first calling powershell executable. (this, I am a little doubtful on but quite sure its correct).
What you can do from ruby is, should work,
PSoutput = system("powershell get-childitem -Recurse -File -Path " + #{path_str} + " | Measure-Object | % {$_.Count}")
Once the command executes, you should have a total number of files under the #path_str directory.

integrating FTP request in powershell script instead of calling .CMD file

Right now I have a powershell script that is callign an FTP request bundled in a CMD file.
It works, but I want to integrate the FTP request in the powershell script because it'll give me 1 less file to keep track of.
So far I have tried doing this, but it produces an error (see below).
# run the command script to extract the file
#defines command to be run
$command = '
#echo off
setlocal
set uname=name
set passw=pass
set hostname=hstname
set filespec=spec
echo %uname%> test.ftp
echo %passw%>> test.ftp
echo cd DIRNAME>> test.ftp
echo binary>> test.ftp
echo get %filespec%>> test.ftp
echo bye>> test.ftp
ftp -s:test.ftp %hostname%
if errorlevel 1 pause
endlocal
'
# runs command
iex $command
Error:
Invoke-Expression : The splatting operator '#' cannot be used to
reference variables in an expression. '#echo' can be used only as an
argument to a command. To reference variables in an expression use
'$echo'. At
Dir\File.ps1:32
char:4
+ iex <<<< $command
+ CategoryInfo : ParserError: (echo:String) [Invoke-Expression], ParseException
+ FullyQualifiedErrorId : SplattingNotPermitted,Microsoft.PowerShell.Commands.InvokeExpressionCommand
I also tried changing the script to $echo but it produces the following error:
Invoke-Expression : Unexpected token 'off' in expression or statement.
At
Dir\File.ps1:32
char:4
+ iex <<<< $command
+ CategoryInfo : ParserError: (off:String) [Invoke-Expression], ParseException
+ FullyQualifiedErrorId : UnexpectedToken,Microsoft.PowerShell.Commands.InvokeExpressionCommand
Alex,
This may not be exactly what you want but here is how I could make it work.
Once you have the commands, pipe all of them to create a batch file. For example:
Set-Content -path $env:temp\mycommands.cmd -value $command
Then, execute that file
iex "cmd /c $env:temp\mycommands.cmd"
The reason what you are doing is not working is because each of these lines are still getting interpreted by PowerShell and some of them have meanings in PowerShell that is not matching what is in CMD shell.

Executing a simple powershell command on the command line

I try to run a simple powershell command by setting a variable and printing it.
This is what I want to do:
powershell -command "& {$name=\"hi\"; echo $name}"
But it fails with:
The string is missing the terminator: ".
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
The invoke operator (&) works fine with commands such as:
powershell -command "& {&echo hi}"
I read about the invoking operator and how to execute commands with -command option and executing scripts with -File option etc. They are working as expected. But my attempts to do the same for setting a variable and printing it as above doesn't work. I suspect -command works with only commands. Any idea how to achieve what I do above?
from a DOS shell this works:
powershell -command "& {$name='hi'; echo $name}"
but also your code works.
From a Powershell console use this:
powershell -command {$name='hi'; echo $name}

Escape special chars in powershell commands

I am new to powershell, but I am facing a very basic problem. When I am running the following command powershell complains. It seems to have issues with the special chars: [*, =, &, <, >]. Any ideas how do I escape them ? This is powershell version 2. [I am using winexe to run the powershell command from a linux box. If I copy paste the ps command it seems to work fine, but remotely running it cause powershell to complain.]
winexe "cmd /c echo . | powershell Set-ExecutionPolicy bypass -Force -Scope CurrentUser;C:\test.ps1 -name 'B*=&<+>%N' -extra_logging '0' "
dos charset 'CP850' unavailable - using ASCII The string starting: At line:1 char:106 + Set-ExecutionPolicy bypass -Force -Scope CurrentUser;C:\test.ps1 -lun <<<< 'B*= is missing the terminator: '. At line:1 char:110 + Set-ExecutionPolicy bypass -Force -Scope CurrentUser;C:\test.ps1 -lun 'B*= <<<< + CategoryInfo : ParserError: (B*=:String) [], ParentContainsErro rRecordException + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
The system cannot find the file specified. The system cannot find the file specified.
The problem isn't powershell but the regular command shell. Making a reasonable assumption about what winexe does, the relevant part of the command is
cmd /c echo . | powershell Set-ExecutionPolicy bypass -Force -Scope CurrentUser;C:\test.ps1 -name 'B*=&<+>%N' -extra_logging '0'
which contains some special characters interpreted by the command shell. Content in single quotes is not considered to be quoted, so you'll need to explicitly quote them. Just to make life difficult, because you're using piping, the characters are processed twice so you'll need to double-quote:
cmd /c echo . | powershell Set-ExecutionPolicy bypass -Force -Scope CurrentUser;C:\test.ps1 -name 'B*=^^^&^^^<+^^^>^%N' -extra_logging '0'
The caret makes the command shell take the following character literally.
Or, if it so happens winexe passes the command it is given to the command shell rather than executing it directly, you might need to triple-quote, i.e., seven carets before each special character.
I could be wrong, but I believe it is the backwards apostrophe or the grave symbol, i.e. `

Resources