简体   繁体   中英

Trouble calling powershell script from within powershell with arguments

I have spent the last 4 hours on this issue and would greatly appreciate any input you might have.

I need to call a powershell script with different credentials and pass arguments onto that script. Following the installation of a program wrapped in WISEScript this script kicks off to gather AD accounts for the machine and remove them from specific AD Security Groups. Unfortunately as the script runs locally I cannot use ActiveDirectory modules in powershell as not all machines in our environment have RSAT. The initial script is run from an elevated account on the machine:

$creds = New-Object System.Management.Automation.PsCredential("DOMAIN\USER", (ConvertTo-SecureString "Password" -AsPlainText -Force))
$ProfileGUIDS = Get-ChildItem 'hklm:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileGuid'
$Groups = [ADSI]"LDAP://CN=Group4d_test,OU=GroupMigrationTesting,OU=TestOU,OU=US,DC=DOMAIN",[ADSI]"LDAP://CN=Group3d_test,OU=GroupMigrationTesting,OU=TestOU,OU=US,DC=DOMAIN"
Function Get-DistinguishedName ($strUserName) 
{  
    $searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'') 
    $searcher.Filter = "(&(objectClass=User)(samAccountName=$strUserName))" 
    $result = $searcher.FindOne() 
    if ($result)
    {
        Return $result.GetDirectoryEntry().DistinguishedName 
    }
} 

forEach ($GUIDkey in $ProfileGUIDS)
{
    $GUID = Out-String -InputObject $GUIDKey
    $index = $GUID.IndexOf("S-1")
    $GUID = $GUID.Substring($index)
    $GUID = $GUID.Substring(0,128)
    $index = $GUID.IndexOf(" ")
    $GUID = $GUID.Substring(0,$index)
    $Profile = "hklm:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$GUID"
    $ProfileItems = Get-ItemProperty $Profile
    $SAM = $ProfileItems.ProfileImagePath
    $index = $SAM.LastIndexOf("\")
    $index ++
    $SAM = $SAM.substring($index)

    $UserDN = Get-DistinguishedName $SAM
    $User = [ADSI]"LDAP://$UserDN"
    if($User -ne $null)
    {
        forEach($group in $groups)
        {

Right here is where I need to call the 2nd script with different credentials.

This is RemoveUsers.ps1, the script I need to run with different credentials:

param
(
    [string]$group = "MyDefaultSAM",
    [string]$user = "MyDefaultUser"
)
$Group.remove($User.ADsPath)

I have tried:

 start-process powershell.exe -Credential $creds -NoNewWindow -ArgumentList "Start-Process $PSSCriptRoot\RemoveUsers.ps1 -Verb

This will run the script however I cannot specify any arguments

powershell.exe -file "$PSScriptRoot\RemoveUsers.ps1" -user $user -group $group

This calls the script with arguments but does not allow for the -Credentials switch

I have also tried:

$job = Start-Job -ScriptBlock { 
powershell.exe -file "$PSScriptRoot\RemoveUsers.ps1" -user $user -group $group
} -Credential $creds

This runs but does not appear to work properly as the users remain in the AD groups.

Any help is appreciated.

Thanks - Jeff

**** UPDATE **** Thanks for the information. When I add the changes you suggest I receive an error

Invoke-Command : Parameter set cannot be resolved using the specified named parameters 

It appears, as I have found online, the -Credential switch cannot be used without the -Computer switch. If I specify $env:COMPUTERNAME or localhost for the computer I receive the error

\RemoveUsers.ps1 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

I can avoid this issue if I remove the -Credential switch and open the AD group to everyone. At this point I don't need to elevate a new powershell script and can add the command in the same. If I cannot resolve the issue with Invoke-Command this is likely what I will do.

**** UPDATE **** What I ultimately had to do was use -Authentication Credssp in the argument list as there is an issue with using the AD Module via Invoke-Command. In addition I had to start the Win-RM service, Enable WSMacCredSSP (-role client on each machine and add a DelegateComputer entry and -role server on the server connecting to). Only after the service was started and an entry was made for WSManCredSSP was I able to use the Invoke-Command switch and have the AD Module work correctly.
This of course makes things more complicated and I decided just installing the AD Module on each PC (after finding a way to do it without RSAT) and forgetting about running the command remotely all together. Thanks for your help with the matter. Thanks

You don't need to run PowerShell scripts with powershell.exe when calling them from another PowerShell script. Simply use the call operator ( & ). Also, I'd use Invoke-Command for running something inline with different credentials.

Beware that the scriptblock doesn't automatically know about the variables in the rest of your script. You need to pass them into the scriptblock via the -ArgumentList parameter. That is most likely the reason why removal didn't work when you ran RemoveUsers.ps1 as a job.

Something like this should work:

Invoke-Command -ScriptBlock {
  & "$PSScriptRoot\RemoveUsers.ps1" -user $args[0] -group $args[1]
} -ArgumentList $user, $group -Credential $creds -Computer $env:COMPUTERNAME

This requires PSRemoting, though (run Enable-PSRemoting as an administrator).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM