Powershell, interactively invoking a static method - powershell

I'm sitting at a PowerShell command prompt and following http://technet.microsoft.com/en-us/library/dd347632.aspx
PS C:\> [System.Math]::Sqrt (9)
Unexpected token '(' in expression or statement.
At line:1 char:22
+ [System.Math]::Sqrt ( <<<< 9)
+ CategoryInfo : PArserError: ((:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
Am I being tricked or did the tutorial give me something that has a syntax error?
How do I do a basic thing like invoke a static method?

Don't have the space after Sqrt:
[System.Math]::Sqrt(9)

Related

How to call a powershell script to another powershell script with arguments?

I just need to call another script and pass the parameters to it.
I tried doing invoke-expression to access it, i tried using &, and nothing worked
I tried doing the following:
$hostfile = "C:\Users\username\Desktop\csvfile_test.csv"
$outFile = ".\testerFile.xlsx"
& '.\organizer.ps1' "-csvFile $hostfile -outputPath $outFile "
Invoke-Expression 'C:\Users\username\Desktop\organizer.ps1' "$hostfile $outFile"
I receive the following errors:.
with ampersand (&):
PS C:\Users\username\Desktop> C:\Users\username\Desktop\scanner.ps1
Exception calling "ReadLines" with "1" argument(s): "The given path's format is not supported."
At C:\Users\username\Desktop\scanner.ps1:48 char:1
+ [System.IO.File]::ReadLines("$csvFile") | ForEach-Object {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NotSupportedException
with invoke-expression:
Exception calling "ReadLines" with "1" argument(s): "The given path's format is not supported."
At C:\Users\username\Desktop\scanner.ps1:48 char:1
+ [System.IO.File]::ReadLines("$csvFile") | ForEach-Object {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NotSupportedException
Invoke-Expression : A positional parameter cannot be found that accepts argument 'C:\Users\username\Desktop\csvfile_test.csv .\testerFile.xlsx'.
At C:\Users\username\Desktop\scanner.ps1:69 char:1
+ Invoke-Expression 'C:\Users\username\Desktop\organizer.ps1' "$host ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Expression], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeExpressionCommand
When you write this:
& '.\organizer.ps1' "-csvFile $hostfile -outputPath $outFile "
you are passing a single parameter to the script (one quoted string). That's not what you want.
This is what you need:
$hostfile = "C:\Users\username\Desktop\csvfile_test.csv"
$outFile = ".\testerFile.xlsx"
.\organizer.ps1 -csvFile $hostfile -outputPath $outFile
First, you don't need the & (invocation) operator because your command name (the organizer.ps1 script in the current location, in this example) doesn't contain spaces. (You can add it if you want, but it's unnecessary in this scenario.)
Second, the -csvFile and -outputPath parameters each require a string.

How to escape "at sign" (#) in Invoke-Expression -Command?

When I run this command in command-line, it works as expected:
C:\>p4 changes #2019/01/16,#now
...
But when I use it in powershell script, I can't get it working.
First attempt:
PS C:\> Invoke-Expression -Command "p4 changes #2018/01/16, #now"
Invoke-Expression : At line:1 char:25
+ p4 changes #2018/01/16, #now
+ ~~~~
Splatted variables like '#now' cannot be part of a comma-separated list of arguments.
At line:1 char:1
+ Invoke-Expression -Command "p4 changes #2018/01/16, #now"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException
+ FullyQualifiedErrorId : SplattingNotPermittedInArgumentList,Microsoft.PowerShell.Commands.InvokeExpressionCommand
Escaping comma (successfully):
PS C:\> Invoke-Expression -Command "p4 changes #2018/01/16',' #now"
p4 : Unintelligible revision specification '2018/01/16'.
At line:1 char:1
+ p4 changes #2018/01/16',' #now
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Unintelligible ...n '2018/01/16'.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Now I think the problem is in "at character" ("#") being interpreted on some level. But I've failed to escape it using multiple methods. How to achieve this?
UPD Testing your ideas:
Grave Accent:
PS C:\> Invoke-Expression -Command "p4 changes `#2018/01/16',' `#now"
p4 : Unintelligible revision specification '2018/01/16'.
At line:1 char:1
+ p4 changes #2018/01/16',' #now
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Unintelligible ...n '2018/01/16'.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Single quote (problem with comma):
PS C:\> Invoke-Expression -Command 'p4 changes #2018/01/16, #now'
Invoke-Expression : At line:1 char:25
+ p4 changes #2018/01/16, #now
+ ~~~~
Splatted variables like '#now' cannot be part of a comma-separated list of arguments.
At line:1 char:1
+ Invoke-Expression -Command 'p4 changes #2018/01/16, #now'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException
+ FullyQualifiedErrorId : SplattingNotPermittedInArgumentList,Microsoft.PowerShell.Commands.InvokeExpressionCommand
Stop using double quotes, if you have no expandable content then use single quotes. See documentation for about_Quoting_Rules
Otherwise it's as others have said, use the backtick (`).
Working solution:
$cmd = #'
p4 changes #2018/01/16','#now
'#;
Invoke-Expression $cmd

writeerrorexception using measure-command in ucs vcheck report

I'm trying to get this powershell report to work
https://github.com/FooBartn/vCheck-UCS
and the report works fine testing it in powershell ise. But when I try to schedule it using powershell.exe -ExecutionPolicy Bypass -File
I see the error below
C:\Scripts\ucs-vcheck-sdc\Plugins\00
Initialize\00_Connection_Plugin_for_UCS.ps1 : Exception of type
'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At C:\Scripts\ucs-vcheck-sdc\vcheck.ps1:672 char:59
+ ... TR = [math]::round((Measure-Command {$Details = . $_.FullName}).Total
...
+ ~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorExcep
tion
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio
n,00_Connection_Plugin_for_UCS.ps1
C:\Scripts\ucs-vcheck-sdc\vcheck.ps1 :
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorExcep
tion
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio
n,vcheck.ps1
The code being used is
$TTR = [math]::round((Measure-Command {$Details = . $_.FullName}).TotalSeconds, 2)
the basics of the scripts is the main vcheck script call plugins from a folder.And example of what $_.Fullname is
C:\Scripts\ucs-vcheck-sdc\Plugins\80 Finish\999 VeryLastPlugin Used to Disconnect.ps1
This line is actually what runs the plugins.From my research its a problem writing to the standard output, but I can't seem to locate the problem. I've looked at permissions, and I've removed the spaces from some of the other plugins but it doesn't seem to matter. I'm reaching out to the mainainter, but I wanted to see if anyone had an idea of what would be causing this.

Is Set-StrictMode incompatible with parameter blocks?

I've got a simple script
Param([string] $myStringValue)
echo $myStringValue
And when I call it with ./test.ps1 -myStringValue steve, it works just fine.
But if I add Set-StrictMode to the beginning:
Set-StrictMode -Version Latest
Param([string] $myStringValue)
echo $myStringValue
I get the following errors:
> ./test.ps1 -myStringValue steve
The variable '$myStringValue' cannot be retrieved because it has not been set.
At D:\code\cadgraphics\test.ps1:2 char:20
+ Param([string] $myStringValue)
+ ~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (myStringValue:String) [], RuntimeException
+ FullyQualifiedErrorId : VariableIsUndefined
The variable '$myStringValue' cannot be retrieved because it has not been set.
At D:\code\cadgraphics\test.ps1:3 char:10
+ echo $myStringValue
+ ~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (myStringValue:String) [], RuntimeException
+ FullyQualifiedErrorId : VariableIsUndefined
I tried setting $myStringValue beforehand
$myStringValue = ''
Set-StrictMode -Version Latest
Param([string] $myStringValue)
echo $myStringValue
but that just made it choke on the Param block:
Param : The term 'Param' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At D:\code\cadgraphics\test.ps1:3 char:5
+ Param([string] $myStringValue)
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (Param:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
What am I doing wrong?
I believe the problem is that param() needs to be first (or only preceded by certain special statements). Put Set-StrictMode after the param() block.
You can see this in ISE because the syntax highlighting will change param() from dark blue (statement) to blue (cmdlet/function/expression).

PowerShell strange execution error

I've created sample cmdlet as a file.ps1 with logic to check my new inbox emails iterative on required time. But when OS Task scheduler (Windows 7) executed it I get these errors:
The interface is unknown. (Exception from HRESULT: 0x800706B5)At
C:\SCRIPTS\my-userAgent.ps1:7 char:7
+ while($ie.busy -eq $true)
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
Method invocation failed because [System.__ComObject] does not contain a
method named 'Navigate'.At C:\SCRIPTS\my-userAgent.ps1:18 char:2
+ $ie.Navigate($url)
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Navigate:String) [], RuntimeE
xception
+ FullyQualifiedErrorId : MethodNotFound
As far as I understand that they are caused by my COM_obj, But why when I execute the same script from PowerShell_ISE it passes and works without errors!?! I've tried to resolve it by:
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
hoping that is user_privileges related, but no success so far.
Any help will be appreciated.