Is Set-StrictMode incompatible with parameter blocks? - powershell

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).

Related

Powershell Invoke command in a function

Im trying to do an invoke command inside a function, but having difficulty getting defined variables to pass through.
function Set-RemoteLocalAdmin {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$ComputerName,
[String] $UserId
)
$sb = {​
param($userid)
add-LocalGroupMember -Group "Administrators" -Member "$UserId"}
Invoke-Command -ComputerName $ComputerName -Scriptblock $sb -argumentlist $userid
}
Errors:
The term '​' 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.
+ CategoryInfo : ObjectNotFound: (​:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
+ PSComputerName : COMPUTERNAME-1
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.
+ CategoryInfo : ObjectNotFound: (param:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
+ PSComputerName : COMPUTERNAME-1
Member BUILTIN\ was not found in group Administrators.
+ CategoryInfo : ObjectNotFound: (BUILTIN:String) [Add-LocalGroupMember], MemberNotFoundException
+ FullyQualifiedErrorId : MemberNotFound,Microsoft.PowerShell.Commands.AddLocalGroupMemberCommand
+ PSComputerName : COMPUTERNAME-1
What am I missing here?
Thanks in advance.

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

Run script with path based on environment variable

I have environment variable ARTEMIS_HOME set to c:\artemis.
PS C:\artemis_brokers> $env:ARTEMIS_HOME
C:\artemis
Under this directory I have a folder called bin that contains an artemis.cmd script. How can I run this script from anywhere in my PowerShell using the system variable?
I have tried the following with no success:
PS C:\artemis_brokers> $env:ARTEMIS_HOME/bin/artemis
At line:1 char:19
+ $env:ARTEMIS_HOME/bin/artemis
+ ~
You must provide a value expression following the '/' operator.
At line:1 char:19
+ $env:ARTEMIS_HOME/bin/artemis
+ ~~~~~~~~~~~
Unexpected token 'bin/artemis' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpectedValueExpression
PS C:\artemis_brokers> ./$env:ARTEMIS_HOME/bin/artemis
./$env:ARTEMIS_HOME/bin/artemis : The term './$env:ARTEMIS_HOME/bin/artemis'
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 line:1 char:1
+ ./$env:ARTEMIS_HOME/bin/artemis
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (./$env:ARTEMIS_HOME/bin/artemis:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\artemis_brokers> ./$env:ARTEMIS_HOME/bin/artemis.cmd
./$env:ARTEMIS_HOME/bin/artemis.cmd : The term './$env:ARTEMIS_HOME/bin/
artemis.cmd' 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 line:1 char:1
+ ./$env:ARTEMIS_HOME/bin/artemis.cmd
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (./$env:ARTEMIS_HOME/bin/artemis.cmd:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\artemis_brokers> ./"$env:ARTEMIS_HOME/bin/artemis.cmd"
./$env:ARTEMIS_HOME/bin/artemis.cmd : The term './$env:ARTEMIS_HOME/bin/
artemis.cmd' 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 line:1 char:1
+ ./"$env:ARTEMIS_HOME/bin/artemis.cmd"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (./$env:ARTEMIS_HOME/bin/artemis.cmd:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\artemis_brokers> .\$env:ARTEMIS_HOME/bin/artemis
.\$env:ARTEMIS_HOME/bin/artemis : The term '.\$env:ARTEMIS_HOME/bin/artemis'
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 line:1 char:1
+ .\$env:ARTEMIS_HOME/bin/artemis
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (.\$env:ARTEMIS_HOME/bin/artemis:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\artemis_brokers> .\$env:ARTEMIS_HOME/bin/artemis.cmd
.\$env:ARTEMIS_HOME/bin/artemis.cmd : The term '.\$env:ARTEMIS_HOME/bin/
artemis.cmd' 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 line:1 char:1
+ .\$env:ARTEMIS_HOME/bin/artemis.cmd
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (.\$env:ARTEMIS_HOME/bin/artemis.cmd:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\artemis_brokers> .\"$env:ARTEMIS_HOME/bin/artemis.cmd"
.\$env:ARTEMIS_HOME/bin/artemis.cmd : The term '.\$env:ARTEMIS_HOME/bin/
artemis.cmd' 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 line:1 char:1
+ .\"$env:ARTEMIS_HOME/bin/artemis.cmd"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (.\$env:ARTEMIS_HOME/bin/artemis.cmd:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
You need to expand the variable and concatenate the rest of the path into a string before you try to execute. To execute the resulting string, use &, the call operator:
& "$env:ARTEMIS_HOME/bin/artemis.cmd"
Try:
& $env:ARTEMIS_HOME\bin\artemis.cmd

Powershell, interactively invoking a static method

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)