Powershell Invoke-Expression A parameter cannot be found that matches parameter name = "" - powershell

Im trying to invoke a Ps script from antoher script. The scripts are both in the same path.
Also the script I'm trying to invoke takes 4 parameters.
Whem i execute that file from powershell with the parameters, then it works without errors.
But invoking it with the Invoke-Expression Command does not work.
Keep getting the error :
'A parameter cannot be found that matches parameter name'
Script with the Paramters :
param ([Parameter(Mandatory = $true)]
[string] $Samname,
[string] $Fullname,
[string] $Password,
[string] $Groups
)
$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force
New-localuser -name $Samname -FullName $Fullname -password $securePassword -PasswordNeverExpires -UserMayNotChangePassword
#Add the User to the Groups
$localGroups = Get-LocalGroup
[string[]]$GroupArray = $Groups.Split(' ')
foreach ($localgroup in $localGroups){
foreach ($group in $GroupArray){
$group = $group.Replace(';', '')
if ($group.toString().Equals($localgroup.toString())){
Add-LocalGroupMember -Group $localgroup -Member $samname
}
}
}
Script with Invoke-Expression command :
$XmlDocument = 'C:\SomeFile\toPs\TmpUser.config'
[XML]$XmlFile = Get-Content $XmlDocument
[string] $Samname = $XmlFile.User.Username
[string] $Fullname = $XmlFile.User.Fullname
[string] $Password = $XmlFile.User.Password
[string] $Groups = $XmlFile.User.Groups
$script = ".\CreateUser.ps1"
Invoke-Expression $script "-Samname $Samname -Fullname $Fullname -Password $Password -Groups $Groups"
I'm not that sure if I'm using the params the right way, when I invoke the script.
Thanks for your help :)

It's hard to tell exactly what's tripping up Invoke-Expression without the full extent of the error message, but the good news is that you don't need Invoke-Expression at all!
Use the invocation operator (also known as the "call operator", &) instead, it natively supports parameter binding:
$XmlDocument = 'C:\SomeFile\toPs\TmpUser.config'
[XML]$XmlFile = Get-Content $XmlDocument
[string] $Samname = $XmlFile.User.Username
[string] $Fullname = $XmlFile.User.Fullname
[string] $Password = $XmlFile.User.Password
[string] $Groups = $XmlFile.User.Groups
$script = ".\CreateUser.ps1"
& $script -Samname $Samname -Fullname $Fullname -Password $Password -Groups $Groups

Related

add random passwortgenerator in the same function

Is it possible to add a random password generator in this function?
Function Create-User([String] $Username, [String] $Name, [String] $Surname, [String] $OU, [String] $Group){
$User = Get-ADUser -Filter {sAMAccountName -eq $Username}
}
I added the $password variable inside of your function that you can use however you choose. The value stored in the variable is a secure string. If you need to provide the password value to the user, you can capture the value first by not piping into the ConvertTo-SecureString cmdlet.
Function Create-User([String] $Username, [String] $Name, [String] $Surname, [String] $OU, [String] $Group){
$password = ((33..126) | ForEach-Object {[char]$_} | get-random -count 20) -join "" | ConvertTo-SecureString -asplaintext -force
New-AdUser -accountpassword $password # You will need to add the rest of your parameters here
}
You can change the -count value to whatever meets your security policy requirements. The example above generates a 20 character password using random characters from the ASCII table positions 33 through 126. You are free to update that range however you see fit.
You could add a small function to generate a password.
Below code creates a password with a mixture of uppercase- and lowercase letters, digits and if you want that also symbols.
function New-Password {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[ValidatePattern("[0-9]")]
[int]$Length = 12,
[switch]$IncludeSymbols
)
$pw = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
if ($IncludeSymbols) {
$pw += "!$%^-_:;{}<>#&#]~"
}
return -join ([Char[]]$pw | Get-Random -Count $length)
}
Use in your Create-User function like this:
Function Create-User {
[CmdletBinding()]
param(
[String]$Username,
[String]$Name,
[String]$Surname,
[String]$OU
)
# call the New-Password function to get a plain text password.
$plainTextPassword = New-Password -Length 8
$securePassword = $plainTextPassword | ConvertTo-SecureString -AsPlainText -Force
# the New-AdUser cmdlet has many parameters. Best use splatting for these.
$splat = #{
SamAccountName = $Username
Name = $Name
Surname = $Surname
Path = $OU
AccountPassword = $securePassword
# add more parameters as you see fit here
# see https://learn.microsoft.com/en-us/powershell/module/addsadministration/new-aduser?view=win10-ps
}
New-AdUser #splat
# output the user and the generated password because you will not be able to retrieve this later..
[PSCustomObject]#{
User = $Username
Password = $plainTextPassword
}
}
Example:
Create-User -Username jdoe -Name 'John Doe' -Surname Doe -OU 'OU=Users, OU=DepartmentX, DC=yourdomain, DC=com'
will output
User Password
---- --------
jdoe 4Wvhud02

Copy files from one folder to another remotely in PowerShell

I want to copy files from one folder on F: to H: on a remote machine. I write the following script but not working, tried with list down all the files, but am getting following error:
Create-Credentials : The term 'Create-Credentials' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
For example:
My remote server is 143.56.23.99
User name : jyoti
Password: Test123#
Source File: F:\SourceFolder\
Destination : H:\Destination\
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)] [string] $Computer,
[Parameter(Mandatory=$True)] [string] $Path,
[Parameter(Mandatory=$True)] [string] $Destination,
[Parameter(Mandatory=$True)] [string] $Username,
[Parameter(Mandatory=$True)] [string] $Password,
[Parameter(Mandatory=$False)] [PSCredential] $Credential
)
if($UserName -and $Password) {
$Credential = Create-Credentials -Username $Username -Password $Password
} elseif(-not ($Credential)) {
throw("Unable to authenticate. A username and password or pscredentials must be provided.")
}
$Items = (Get-ChildItem $Path).FullName
$NetworkLocation = Join-Path -Path "\\$Computer" -ChildPath ($Destination.Replace(':', '$'))
foreach ($Item in $Items) {
Write-Host "------------>$Item"
}
I'd recommend reading up on using Credentials as it will help you understand what's going on with your code.
Create-Credentials is not a native powershell cmdlet, either go back to where you got your code from and get that function too.
Or remove the function and use native powershell code.
Replace:
$Credential = Create-Credentials -Username $Username -Password $Password
with:
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,($Password | ConvertTo-SecureString -AsPlainText -Force)

Issues passing credentials to a function Azure Powershell

Hi all I'm trying to pass server login credentials to my 'createSQLServer function but keep hitting the error 'Cannot process argument transformation on parameter 'creds'.userName'' I've tried a lot of different, even tried with a 'param block' but stull stuck. A push in the right direction would be appreciated, cheers.
###### SQL SERVER LOGIN CREDENTIALS
$userName = "aaron"
$password = "Password_1234"
$securePassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $securePassword
### SQL server names with resource group name appeneded
$server1 = "sqlserver1" + $resGroup
$serVerion = "12.0"
function createSQLserver ([string]$server1,[string]$server2, [string]$server3, [System.Management.Automation.PSCredential]$creds,[string]$server1Location, [string]$server2Location, [string]$server3Location, [string]$resGroup, [string]$serVerion, [string]$userName, [string]$password, [SecureString]$securePassword)
{
#Create server 1(Server A)
<#check to see if server exists - It exists, $continue is created and passed to
if statement to append two random characters to name#>
Write-Host "Creating First SQL Server"
$sqlServer = New-AzureRmSqlServer -ServerName $server1 -SqlAdministratorCredentials $creds -Location $server1Location -ResourceGroupName $resGroup -ServerVersion $serVerion -ErrorVariable continue -ErrorAction SilentlyContinue
if ($continue)
{
do {
$server1 = $server1 + (rand)
$sqlServer = New-AzureRmSqlServer -ServerName $server1 `
-SqlAdministratorCredentials $creds -Location $server1Location `
-ResourceGroupName $resGroup -ServerVersion "12.0" -ErrorVariable continue -ErrorAction SilentlyContinue
}
until(!$continue)
Write-Host 'exists creating new' $server1 'Created'
}else{
Write-Host $server1 ' Created'
}
Start-Sleep -s 2
}
createSQLserver $server1 $username $password $securePassword $creds $server1Location $resGroup $serVerion
You need to use your named parameters!
Here's a snippet of your first few parameters:
...
[string]$server1
,
[string]$server2
,
[string]$server3
,
[System.Management.Automation.PSCredential]$creds
...
And then the ones you're passing in to the function call
createSQLserver $server1 $username $password $securePassword ...
So because you're not using the names of your parameters, they are using their relative ordinal position i.e.
param | value
---------+----------------
$server1 | $server1
$server2 | $username
$server3 | $password
$creds | $securePassword
So what have we learned?
Always use named parameters!
createSQLserver -server1 $server1 -username $username -password $password -securePassword $securePassword
That should sort you out :-)

Powershell not recognizing boolean argument

I have the following PS script
param (
# FQDN or IP address of the Domain Controller
[Parameter(Mandatory=$True)]
[string]$ADaddress,
# Active directory domain name
# example: directory.local
[Parameter(Mandatory=$True)]
[string]$ADDomainName,
# Domain admin
# example: administrator#directory.local
[Parameter(Mandatory=$True)]
[string]$domainAdmin,
# Domain admin password
[Parameter(Mandatory=$True)]
[string]$domainAdminPassword,
# User to be added
# example: testUser
[Parameter (Mandatory=$True)]
[string]$newUsername,
# Password of th user to be added
# example: 1!2#4%6
[Parameter (Mandatory=$True)]
[string]$newPassword,
# SAM account name of the user to added
# example: testuser
[Parameter (Mandatory=$True)]
[string]$newSamAccountName,
# Display name of the user to added
# example: "Test user for test purposes"
[Parameter (Mandatory=$True)]
[string]$newUserDisplayName
)
$domainAdminSecurePassword = $domainAdminPassword | ConvertTo-SecureString -asPlainText -Force
$domainAdminCredential = New-Object System.Management.Automation.PSCredential($domainAdmin, $domainAdminSecurePassword)
$newUserSecurePassword = $newPassword | ConvertTo-SecureString -asPlainText -Force
$UPN= $newUsername+"#"+$ADDomainName
Invoke-Command -ComputerName $ADaddress -Credential $domainAdminCredential `
-ScriptBlock {`
param($newUsername, $newUserSecurePassword, $newSamAccountName, $newUserDisplayName, $UPN) `
new-aduser -name $newUsername -AccountPassword $newUserSecurePassword -Enabled $true -SamAccountName $newSamAccountName -DisplayName $newUserDisplayName -UserPrincipalName $UPN -PasswordNeverExpires $true`
} `
-ArgumentList $newUsername, $newUserSecurePassword, $newSamAccountName, $newUserDisplayName, $UPN
Tho problem I get when invoking this script is:
Cannot convert 'System.String' to the type 'System.Nullable`1[System.Boolean]' required by parameter 'PasswordNeverExpires'.
I tried passing 1 instead, passing [bool]$true but the result remains the same. I am new to PS and I'm lost here. Can anyone shine some light on what the problem may be?
Alright, I found what the problem was.
Changed:
-PasswordNeverExpires $true`
to
-PasswordNeverExpires $true `
(added a space after true)
replacing $true with a variable did it for me.
So this:
$command = 'New-CMApplicationDeployment -Name $Name -CollectionName $Col -OverrideServiceWindow $true -Comment $Com -AvailableDateTime $Adt -DeployAction Install -DeployPurpose Available -UserNotification DisplaySoftwareCenterOnly'
Invoke-Expression -Command "& $command"
became:
$t = $true
$command = 'New-CMApplicationDeployment -Name $Name -CollectionName $Col -OverrideServiceWindow $t -Comment $Com -AvailableDateTime $Adt -DeployAction Install -DeployPurpose Available -UserNotification DisplaySoftwareCenterOnly'
Invoke-Expression -Command "& $command"
Its dumb but it worked.

Publishing results in NUnit tests

I am writing a PowerShell script for multithreading NUnit tests. My problem is that I take test categories from the file category.txt, and I have to write which categories have been done into my output file file 1.txt. I also need to output an XML report after all tests have been performed. How can I do this in NUnit?
$Groups=Get-Content d:\test\category.txt | Select-Object -Last 10
Write-Host $Groups
if ($Groups -ne $null)
{Write-Host "true"}
else
{write-host "false"}
###Multithreading###
$ThreadNumber =$Groups.Count
$ScriptBlock = {
function Nunit {
$Connection = #{"server" = ""; "username" = ""; "password" = ""}
write-verbose $Connection
$serv = $connection.Get_Item("server")
$user = $connection.Get_Item("username")
$pass = $connection.Get_Item("password")
$securePassword = ConvertTo-SecureString -AsPlainText $pass -Force
#Create connection credentials object for Invoke-Command
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user, $securePassword
$Output = "C:\"
$scriptBlock = {
CMD.EXE /C "C:\testNunit\bin\nunit-console.exe /xml:c:\console-test.xml C:\testNunit\dll\Tests.dll /include:TestTypeSmoke> c:\1.txt"
}
Invoke-Command -ComputerName $serv -ScriptBlock $scriptBlock -credential $cred
}
Nunit
}
I will try to get back to you on NUnit after trying some things at my end, but as a suggestion you could also try PowerShell Workflow for Multi-Threading. They work like functions.
Workflow NUnit
{
Param
(
$server,
$username,
$password,
)
foreach -parallel -throttlelimit 2($group in $groups)
try{
//NUnit Code here
}
}
Catch
{
$_.Exception.Message
}
}
}
NUnit-server "" -username "" -password ""