I've created a script to cycle through a spreadsheet with two columns. The problem I'm running into is that the local variables are not working when I run invoke-command
. I've added the -ArgumentList
parameter but I'm still getting an error about $null
arguments. Anyone know what I'm doing wrong here?
foreach ($list in (Import-Csv C:\Users\joerod\Desktop\remove_users.csv)) {
Write-Output "Connecting to $($list.computer)..."
$myses = New-PSSession -ComputerName $list.computer
Invoke-Command -Session $myses -ScriptBlock {
Write-Output "Searching for software..."
Write-Output $list.user
$find_java = gwmi Win32_Product -Filter "Name LIKE '%Java'" | select -ExpandProperty IdentifyingNumber
if ($find_java -ne $null) {
Write-Output "Software found... Uninstalling..."
foreach ($i in $find_mktx) {
msiexec.exe /x $i /qn /passive /l*v! c:\uninst.log
}
Write-Output "Adding $($list.user) to security group"
$group = "CN=Java_removed,OU=Groups,OU=Resources,DC=Contoso,DC=LOCAL"
Add-ADGroupMember $group -Identity $list.user
}
else {
Write-Output "Could not find Java software installed"
}
} -ArgumentList $list
}
The problem is your trying to pass an arguement list into your else
. It's alot easier to see if you format your code properly.
foreach($list in (Import-Csv C:\Users\joerod\Desktop\remove_users.csv)){
Write-Output "Connecting to $($list.computer)..."
$myses = New-PSSession -ComputerName $list.computer
Invoke-Command -Session $myses -ScriptBlock {
Param($list)
Write-Output "Searching for software..."
Write-Output $list.user
$find_java = gwmi win32_product -filter "Name LIKE '%Java'" | select -ExpandProperty IdentifyingNumber
if($find_java -ne $null){
Write-Output "Software found... Uninstalling..."
foreach($i in $find_mktx){
msiexec.exe /x $i /qn /passive /l*v! c:\uninst.log
}
Write-Output "Adding $($list.user) to security group"
$group = "CN=Java_removed,OU=Groups,OU=Resources,DC=Contoso,DC=LOCAL"
Add-ADGroupMember $group -Identity $list.user
}
else{
Write-Output "Could not find Java software installed"
}
} -ArgumentList $list
}