I am trying to create a script which should run using parameter and without parameter should result for for multiple list: Ex: I have a function under which I gave param as servername which is working fine for single server ad fetching the results. (RestoreFileList -servername XXXXXXXXXXX1)
If I do not want to give a parameter as servername and output should result full set of servers list data Ex : Restorefilecount
Am i missing something between parameter and serverlist condition which should fetch the results, Any help on this?
Script *************
function Restorefilecount()
{
[cmdletbinding()]
param(
[Parameter(position = 0,mandatory = $false)]
[string] $Servername
)
$servername = @()
$servername = ('XXXXXXXX1', 'XXXXXXXXX2', 'XXXXXXXXX3', 'XXXXXXXXXX4')
$result = Invoke-Client -ComputerName $Servername -ScriptBlock {
$Server = HOSTNAME.EXE
$Query = @'
Select @@ServerName AS ServerName , name,(SUBSTRING(NAME ,15,3) * 100 ) / 100 AS
file,state_desc,user_access_desc FROM master.sys.databases where name like 'TKT' ORDER BY 2
'@
Invoke-Sqlcmd -ServerInstance $Server -Database master -Query $Query
}
CodePudding user response:
Building on Abraham Zinala's helpful comments:
It looks like you're simply looking to define a parameter's default value:
function Restore-FileCount {
[CmdletBinding()]
param(
[string[]] $Servername = @('XXXXXXXX1', 'XXXXXXXXX2', 'XXXXXXXXX3', 'XXXXXXXXXX4')
)
# ...
$Servername # Output for demo purposes
}
Note how the parameter type had to be changed from [string]
to [string[]]
in order to support an array of values.
Incidental changes:
Since you're using a
param(...)
block to define your parameters (which is generally preferable), there is no need to place()
after the function name (Restorefilecount()
) - while doing so doesn't cause a syntax error as long as there's nothing or only whitespace between(
and)
, note that you declare parameters either via aparam(...)
block or viafunction foo(...)
; also, in parameter-less functions()
is never needed - see the conceptual about_Functions help topic.I've inserted a hyphen (
-
) in your function name, to make it conform to PowerShell's naming convention.I've omitted
[Parameter(position = 0, mandatory = $false)]
, because what this attribute instance specifies amounts to the default behavior (all parameters are non-mandatory by default, andPosition=0
is implied by$ServerName
being the first (and only) parameter).