Powershell script with params *and* functions - powershell

I want to write a powershell script that takes in params and uses functions.
I tried this:
param
(
$arg
)
Func $arg;
function Func($arg)
{
Write-Output $arg;
}
but I got this:
The term 'Func' 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 func.ps1:6 char:5
+ Func <<<< $arg;
+ CategoryInfo : ObjectNotFound: (Func:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Fine, I thought. I'll try this instead:
function Func($arg)
{
Write-Output $arg;
}
param
(
$arg
)
Func $arg;
But then, I got this:
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 C:\Users\akina\Documents\Work\ADDC\func.ps1:7 char:10
+ param <<<<
+ CategoryInfo : ObjectNotFound: (param:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Is what I'm asking for doable? Or am I being unreasonable in my request?

The param block in a script has to be the first non-comment code. After that, you need to define the function before you invoke it e.g.:
param
(
$arg
)
function Func($arg)
{
$arg
}
Func $arg
The Write-Output is unnecessary in your example since the default behavior is to output objects to the output stream.

All you need ius to make sure PARAM is first string of your script.

You can put the param tag inside the function..
Something like this:
function func($avg)
{
param
(
$avg
)
}

Related

Parsing a web page for text

I'm trying to search a webpage for a word "Green". It tells me things are fine but if it finds "Red" it tells me things are bad. What I've done below is very simple but I'm thinking its enough to ask the question.
$web = Invoke-WebRequest http://myip/vrsinfo/aghealth/DISTAGAR
$web.ToString() -split "[`r`n]" | Select-String "Green"
Here is what it returns
name="agSolarwindsHealth" value=Green readonly>
Here is what I've tried so far
if (name="agSolarwindsHealth" value=Green readonly>) {
'This number is 1'
} else {
'This number is not 1'
}
Error
name=agSolarwindsHealth : The term 'name=agSolarwindsHealth' 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:3 char:5
+ if (name="agSolarwindsHealth" value=Green readonly>)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (name=agSolarwindsHealth:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Powershell scripting help needed

I am very new to powershell scripting. Trying to learn it from web. Now I am trying to do a script and facing some problem, so need some help ans suggestions from you people. I am giving description what I tried to do:
first of all I have declared 2 variables, then I used if statement to see if the variables are empty then it will show a warning message and it will ask for the inputs from the user and after that it will show the value of the variables. but it is giving some errors.
$workingdirectory = args[0]
$directoryname = args[1]
if ("$WorkingDirectory" -eq "")
{
Write-Warning "Parameter Required"
$WorkingDirectory = Read-Host "Enter the absolute path to working directory "
}
if ("$DirectoryName" -eq "")
{
Write-Warning "Paramater Required"
$DirectoryName = Read-Host "Enter a directory name to search for in $WorkingDirectory "
}
Write-Host "$WorkingDIrectory"
write-host "$DirectoryName"
When I run it, it is showing the following errors:
ARGS[0] : The term 'ARGS[0]' 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 C:\LAB_5-submission\mmbillah1_Lab_testdir.ps1:24 char:21
+ $WorkingDirectory = ARGS[0]
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (ARGS[0]:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
ARGS[1] : The term 'ARGS[1]' 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 C:\LAB_5-submission\mmbillah1_Lab_testdir.ps1:25 char:18
+ $DirectoryName = ARGS[1]
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (ARGS[1]:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I want to run like this: .\scriptname.ps1, if I use this then it will show the warning and ask for the two variables input.
and if I run this .\scriptname.ps1 C:\users\masum then it will ask for the second variable value only.
The root of your problem is simply syntax it should be $args[0] and $args[1] if you intend to use what you have now. What I would strongly suggest instead is to create parameters for your script, and then test if those parameters are valid, and if they aren't to prompt for them.
Parameters can be defined in a Param() block as such:
Param(
$workingdirectory,
$directoryname
)
That is very simple, but for your needs it works. You can add types to make sure the right kinds of things are passed as the parameter, and add tests to make sure the parameters are valid, but that goes beyond what we're doing here.
Then you would check to make sure that there is a value for each, and I would recommend making sure that the path is valid. Something like:
While([string]::IsNullOrEmpty($workingdirectory) -or !(Test-Path $workingdirectory)){
$workingdirectory = Read-Host "Enter a valid working directory"
}
That checks if the $workingdirectory variable is empty or just blank spaces, and if it actually has a value it will check to make sure it's a valid directory. If it is blank or the path isn't valid it prompts the user to enter a valid path. You would need to repeat that for the $directoryname variable.
So you would end up with something like:
Param(
$workingdirectory,
$directoryname
)
While([string]::IsNullOrEmpty($workingdirectory) -or !(Test-Path $workingdirectory)){
$workingdirectory = Read-Host "Enter a valid working directory"
}
While([string]::IsNullOrEmpty($directoryname) -or !(Test-Path $directoryname)){
$directoryname= Read-Host "Enter a valid target directory"
}
Write-Host $workingdirectory
Write-Host $directoryname

PowerShell Native Cmdlet Set-Alias with Function and Switch

Question:
Is it possible to set an alias that calls both a function and a switch?
Here is an example I am working with.
Set-Alias -Name myidea -Value 'Test-FunctionIdea -SwitchIdea'
function Test-FunctionIdea {
param(
[switch]$SwitchIdea
)
if($SwitchIdea)
{
Write-Host 'Good Idea'
}
}
Here is the error I am having:
myidea : The term 'Test-FunctionIdea -SwitchIdea' 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
+ myidea
+ ~~~~~~
+ CategoryInfo : ObjectNotFound: (Test-FunctionIdea -SwitchIdea:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
If it is possible please let me know how it's done. I've searched the internet for this and came up with no results.
You can check $MyInvocation.InvocationName and adjust the parameters inside the function:
function Some-Function([switch] $foo) {
if ($MyInvocation.InvocationName -eq 'foo') { $foo = $true }
}
Set-Alias foo Some-Function
The [usually negligible] advantage is that it doesn't create an additional execution context for the new function scope.

Why passing args from powershell gives error while working from inside script itself

Why calling .\MyScript.ps1 -Uninstall from Powershell gives an error
+ Super-Function $Args
+ ~~~~~
+ CategoryInfo : InvalidData : (:) [Super-Function], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Super-Function
While calling "Super-Function" from the script itself with Super-Function -Uninstall , replacing $Args with the switch works ?
Why copy pasting the function on Powershell and then going for Super-Function -Uninstall works too ?
Here's the content of MyScript.ps1
function Super-Function([parameter(Mandatory=$False)][ValidateScript({Test-Path _$})][String]$var1 = ".\MyFile.ext",
[parameter(Mandatory=$False)][ValidateScript({Test-Path _$})][String]$var2 = "HKLM:\SOFTWARE\Wow6432Node\Publisher\SoftwareName",
[parameter(Mandatory=$False)][ValidateScript({([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")})][Switch]$Uninstall,
[parameter(Mandatory=$False)][ValidateScript({([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")})][Switch]$Install
)
{
}
Super-Function $Args
You have a few issues there that I see. Your ValidateScript for each argument have an issue. First, might just be a typo, you have the characters backwards for current pipe item. Should be $_ instead of _$. Next I find it befuddling that you test the presence of the admin role against a couple of boolean switches. Lets just move that inside the function (If what you had works that is fine. Just does make much sense)
Lastly, and most importantly, what you are trying to do with $args is called splatting. Use #args which will splat the hashtable of arguments, passed in from the script, against the function.
function Super-Function{
param(
[parameter(Mandatory=$False)][ValidateScript({Test-Path $_})][String]$var1 = ".\MyFile.ext",
[parameter(Mandatory=$False)][ValidateScript({Test-Path $_})][String]$var2 = "HKLM:\SOFTWARE\Wow6432Node\Publisher\SoftwareName",
[parameter(Mandatory=$False)][Switch]$Uninstall,
[parameter(Mandatory=$False)][Switch]$Install
)
# Use this to verify what has been assinged to your parameters. Will not show default values.
#$PSBoundParameters
If(([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){
"Sure"
} Else {
Throw "Nope"
}
}
Super-Function #args

PowerShell error 'can't call null-value expresssion' [duplicate]

I am simply trying to create a powershell script which calculates the md5 sum of an executable (a file).
My .ps1 script:
$answer = Read-Host "File name and extension (ie; file.exe)"
$someFilePath = "C:\Users\xxx\Downloads\$answer"
If (Test-Path $someFilePath){
$stream = [System.IO.File]::Open("$someFilePath",[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
$hash = [System.BitConverter]::ToString($md5.ComputeHash($stream))
$hash
$stream.Close()
}
Else{
Write-Host "Sorry, file $answer doesn't seem to exist."
}
Upon running my script I receive the following error:
You cannot call a method on a null-valued expression.
At C:\Users\xxx\Downloads\md5sum.ps1:6 char:29
+ $hash = [System.BitConverter]::ToString($md5.Compute ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
To my understanding, this error means the script is attempting to do something, but another part of the script does not have any information to permit the first part of the script to work properly. In this case, $hash.
Get-ExecutionPolicy outputs Unrestricted.
What is causing this error?
What exactly is my null valued expression?
Any help is appreciated. I apologize if this is trivial and will continue my research.
References:
http://blogs.technet.com/b/heyscriptingguy/archive/2013/03/27/troubleshoot-the-invokemethodonnull-error-with-powershell.aspx
How to get an MD5 checksum in PowerShell
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.