Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Write-output format

$
0
0

Hi,

I'v very simple code to see if a server is a replica server

$vmname=Get-vm | where { $_.Replicationmode -eq “replica”} | select name
write-output $vmname | Out-file C:\temp\serverlist.txt

When i start the script the output is like this

Name
----

Server1

server 2

server 3  

But i only want to have the server names like this

server1
server2
server3

How do I do this?



Inserting groups from one into another

$
0
0

Hi together,

I am new in PowerShell Scripting and hope I am correct here for my question.

I'd like to describe you what I'd like to do:

1) There are two different OUs in AD. I'd like to Name them like that:

AD: ad.example.com

first OU: "USR > ORG"

second OU: "USR > SYNC"

2) In each OU ( in ORG and in SYNC), there are many global security groups with the same naming convention:

Naming convention in ORG:

<2 to 4 characters>-All-Users

(Examples: ABC-All-Users, XYZ-All-Users, KK-All-Users, DDDD-All-Users, etc.)



Naming convention in SYNC:

SYNC-<the same 2 to 4 characters of the Group in ORG>

(Examples: SYNC-ABC, SYNC-XYZ, SYNC-KK, SYNC-DDDD, etc.)

3) There is also a ROOT-USER in the AD.

My TARGET:

I want to automate by using a PowerShell script that

A) each group from USR should be inserted in to the related Group in SYNC

(Examples: ABC-All-Users into SYNC-ABC, XYZ-All-Users into SYNC-XYZ, KK-All-Users into SYNC-KK, DDDD-All-Users into SYNC-DDDD, etc.)

and

B) the ROOT-USER should be inserted to all groups in SYNC.

(Example: ROOT-USER is a member of SYNC-ABC,SYNC-XYZ, SYNC-KK, SYNC-DDDD, etc.)

How can I realize such Kind of PowerShell script?

I hope somebody can help me.

Best Regards

Birdal 

Appending description with LastLogonTimestamp

$
0
0
Get-ADUser -Filter * -SearchBase "OU=Test,OU=marketing,OU=Disabled Accounts,DC=test,DC=LOC" -Prop Description,lastLogonTimestamp | Foreach {Set-ADUser $_ -Description ($_.Description + "-" + {[datetime]::FromFileTime($_.lastLogonTimestamp)})}

I am trying to update the description of al users in an OU to include the timestamp.

Any advice is greatly appreciated

API to copy Nuget packages to local folder using Powershell

$
0
0

Hi,

I'm new to powershell and I want to copy some selected packages from Nuget(https://www.nuget.org) to our local repository(folder) using Powershell script. This local repository will be used organisation wide to install packages.

Please suggest.

Thanks.


Need help to create VM's parallel using powershell

$
0
0

I am using following code to create VM's sequentially but i am not able to create VM's parallel. Please help me.

[int]$a=1
[int]$b= 101
#Copy the VHD File 
for($i=1;$i -le $a;$i++ )
{
Copy-Item 'G:\NewVHDX2012\WindowsServer2012_EPRs.vhdx' -Destination G:\EPRVMs\VM$i.vhdx

#Created a VM
New-VM –Name Win2012_$i –MemoryStartupBytes 8GB –VHDPath "G:\EPRVMs\VM$i.vhdx" -Path G:\EPRVMs\VM$i  -SwitchName 'Intel(R) 82579LM Gigabit Network Connection - Virtual Switch'
#Start the VM
Start-Sleep -Seconds 2
Start-VM -Name Win2012_$i
Start-Sleep -Seconds 2
if(( (Get-VM Win2012_$i).state -eq 'Running') -and ((Get-VM Win2012_$i).status -eq "Operating normally"))
{
Start-Sleep -Seconds 10
do
{
  
   $IPAddress=(Get-VM -Name Win2012_$i | Select -ExpandProperty NetworkAdapters | Where-Object {$_.SwitchName -like "Intel(R) 82579LM*"} |Select-Object -ExpandProperty IPAddresses -ErrorAction SilentlyContinue)
Start-Sleep -Seconds 5

}while($IPAddress -eq $Null)
}

$IPAddress=(Get-VM -Name Win2012_$i | Select -ExpandProperty NetworkAdapters | Where-Object {$_.SwitchName -like "Intel(R) 82579LM*"} |Select-Object -ExpandProperty IPAddresses -ErrorAction SilentlyContinue)[0]
Echo $IPAddress
F:\PSTools\PsExec.exe \\"$IPAddress" -u Administrator -p hpadmin@123 -w c:\ -h cscript.exe "C:\Users\Administrator\Desktop\test.vbs" | Out-File c:\test.txt
$EthernetName= (Get-Content c:\test.txt | Select-Object -last 1)
F:\PSTools\PsExec.exe \\"$IPAddress" -u Administrator -p hpadmin@123 -w c:\ cmd.exe /c netsh.exe interface ip set address name= "$EthernetName" static 192.168.1.$b 255.255.255.0 192.168.1.1 
$IPAddress = "192.168.1.$b"
F:\PSTools\PsExec.exe \\"$IPAddress" -u Administrator -p hpadmin@123 -w c:\ -h powershell.exe "Rename-Computer -ComputerName "'$env:computername'" -NewName "Test-$b" -F"
F:\PSTools\PsExec.exe \\"$IPAddress" -u Administrator -p hpadmin@123 -w c:\ -h powershell.exe Restart-Computer -F
Start-Sleep -Seconds 90
$b+=1
F:\PSTools\PsExec.exe \\"$IPAddress" -u Administrator -p hpadmin@123 -w c:\ -h powershell.exe "C:\Users\Administrator\Desktop\EPRCreation.ps1" $i
Start-Sleep -Seconds 5
}


How can I use -Continuous in my powershell code inside Visual Studio C# Winforms?

$
0
0

Hi all,

I am using VS2015 C# in a winform. I click a button and run the following code:

txtDiskActivity.Text = RunScript("Invoke-Command -ComputerName " + txtWSName.Text + " -ScriptBlock {Get-Counter -counter '\\LogicalDisk(C:)\\Avg. Disk sec/Write'}");

..the above code displays in a textbox the disk activity for a hard-drive. It works.

What I have being trying to do is add the -Continuous to the code so that it keeps showing the disk activity. But no matter where I place it (somewhere towards end of code) it then doesn't show anything in the textbox.

The following code shows where I place the -Continuous:

txtDiskActivity.Text = RunScript("Invoke-Command -ComputerName " + txtWSName.Text + " -ScriptBlock {Get-Counter -counter '\\LogicalDisk(C:)\\Avg. Disk sec/Write' -Continuous}");

Could someone indicate where I going wrong?

Regards,



Can we get md5 hashes out off Exchange online attachments?

$
0
0
Can we get md5 hashes out off Exchange online attachments?

Migration Script Issue - Please help

$
0
0

The below script is not working from windows 2003 to windows 2008.

  • VBScript used on windows ENV to migrate the users.
  • The script was run on a Windows 2003 machine.
  • Now it has compatible issues in running on Windows 2008 server.
  • The script was last run some 4-5 months back on 2008 server and it failed, now we do not have any

windows 2003 servers.

  • The requirement out here is to come up with a script or, windows PowerShell scripting or, any other mean to migrate the users.

PowerShell ISE Freezes after executing WinForms

$
0
0
Hello, I've been having an issue with my PowerShell ISE. I am currently developing a PowerShell script that generates Windows Forms for gathering and displaying data. From what I can tell, the application runs and works great. However, after I execute the code once in the ISE (and close the app/stop execution gracefully); if I leave the ISE idle, for about 10 minutes, the ISE will freeze and I have to crash it with Task Manager. If winform code has not been executed, ISE works fine indefinitely. Thoughts on why my ISE constantly crashes when working on winform based scripts? Thanks.

No data from $Node using Configuration Data (PSDsc)

$
0
0

Hi guys, I don't know whether I'm just being stupid, or my brain has decided to subconsciously start thinking about lunch. I'm trying to mess around with certificate encryption in the MOF files, for some reason it's still warning me that it's trying to save in plaintext.. What am I doing wrong?! :S

Liam

Host information:

Name             : Windows PowerShell ISE Host
Version          : 5.0.10586.117
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-GB
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.Host.ISE.ISEOptions
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

Code:

configuration Config_Server1
{
    param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [pscredential]$Credential
    )
    node $AllNodes.Where({$_.NodeName -eq "Server1"}).Guid
    {
        WindowsFeature FTPServ {
            Name = "web-ftp-server"
            Ensure = 'Present'
            Credential = $Credential
        }

        File TestFolder {
            DestinationPath = 'C:\TestFolder'
            Type = 'Directory'
            Ensure = 'Present'
            Credential = $Credential
        }
    }
}


$ConfigData = @{
    AllNodes = @(
        @{
            NodeName = "Server1"
            CertificateFile = 'C:\cert\Server1.cer'
            Thumbprint = '404350DED0317B8D8790E0C4E16B0068C02B01E5'
            Guid = '6d29d9c0369b4b3ab0088a7e8db1f2ff'
            Role = 'Basic Server'
        }
    )

}

Config_Server1 -OutputPath C:\DSC\Configs -ConfigurationData $ConfigData -Credential (Get-Credential) -Verbose
Copy-Item -Path C:\DSC\Configs\6d29d9c0369b4b3ab0088a7e8db1f2ff.mof -Destination 'C:\Program Files\WindowsPowerShell\DscService\Configuration' -Force -Verbose
New-DscChecksum -Path 'C:\Program Files\WindowsPowerShell\DscService\Configuration\6d29d9c0369b4b3ab0088a7e8db1f2ff.mof' -Verbose -Force



Setting BusinessCategory Attribute

$
0
0

Hi there,

I need some help for updating some of the ad attribute. I have the following fileadtest2.csv which contain the following information

samaccountname,devision,city,business-category,displayname
chon.kit.wong,ITI,Kuala Lumpur,IT,wong chon kit
trust.gates,CTO,Kuala Lumpur,IT,trust gates

$users = Import-Csv -Path c:\users\administrator\desktop\adtest2.csv 

foreach ($user in $users) {            
#Search in specified OU and Update existing attributes            
 Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" -Properties * -SearchBase "ou=employees,DC=test,DC=com" |            
  Set-ADUser -City $($user.City) -'business-category' $($user.'business-category') -Company $($user.Company) -Displayname $($user.displayname)       
}

I found businesscategory under attribute editor and I was trying to set the entry. However what I have encounter it is the following error

Set-ADUser : A positional parameter cannot be found that accepts argument 'design'.
At C:\Users\Administrator\Desktop\myscript.ps1:26 char:13
+   Set-ADUser <<<<  -City $($user.City) -'business-category' $($user.'business-category') -Company $($user.Company) -D
isplayname $($user.displayname)
    + CategoryInfo          : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADUser

Set-ADUser : A positional parameter cannot be found that accepts argument 'design'.
At C:\Users\Administrator\Desktop\myscript.ps1:26 char:13
+   Set-ADUser <<<<  -City $($user.City) -'business-category' $($user.'business-category') -Company $($user.Company) -D
isplayname $($user.displayname)
    + CategoryInfo          : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADUser

Set-ADUser : A positional parameter cannot be found that accepts argument 'design'.
At C:\Users\Administrator\Desktop\myscript.ps1:26 char:13
+   Set-ADUser <<<<  -City $($user.City) -'business-category' $($user.'business-category') -Company $($user.Company) -D
isplayname $($user.displayname)
    + CategoryInfo          : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADUser

I would appreciate if someone can let me know how I can update the businesscategory portion. Looking forward from the experty in this forum.

Regards,

CK


CK

Throw keyword doesn't throw an error message in the system script that loads SQL SMO assemblies

$
0
0

Howdy,

I am trying to use the PowerShell code provided in the Load the SMO Assemblies in Windows PowerShell article.

However, it looks as if the Throw keyword in this script doesn't throw the specified error message. The script stops execution as prescribed by $ErrorActionPreference, but doesn't throw the 'SQL Server Provider for Windows PowerShell is not installed.' error message.

Let me copy the whole script here

#
# Loads the SQL Server Management Objects (SMO)
#

$ErrorActionPreference = "Stop"

$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

if (Get-ChildItem $sqlpsreg -ErrorAction "SilentlyContinue")
{
    throw "SQL Server Provider for Windows PowerShell is not installed."
}
else
{
    $item = Get-ItemProperty $sqlpsreg
    $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)
}

$assemblylist =
"Microsoft.SqlServer.Management.Common","Microsoft.SqlServer.Smo","Microsoft.SqlServer.Dmf ","Microsoft.SqlServer.Instapi ","Microsoft.SqlServer.SqlWmiManagement ","Microsoft.SqlServer.ConnectionInfo ","Microsoft.SqlServer.SmoExtended ","Microsoft.SqlServer.SqlTDiagM ","Microsoft.SqlServer.SString ","Microsoft.SqlServer.Management.RegisteredServers ","Microsoft.SqlServer.Management.Sdk.Sfc ","Microsoft.SqlServer.SqlEnum ","Microsoft.SqlServer.RegSvrEnum ","Microsoft.SqlServer.WmiEnum ","Microsoft.SqlServer.ServiceBrokerEnum ","Microsoft.SqlServer.ConnectionInfoExtended ","Microsoft.SqlServer.Management.Collector ","Microsoft.SqlServer.Management.CollectorEnum","Microsoft.SqlServer.Management.Dac","Microsoft.SqlServer.Management.DacEnum","Microsoft.SqlServer.Management.Utility"

foreach ($asm in $assemblylist)
{
    $asm = [Reflection.Assembly]::LoadWithPartialName($asm)
}

Push-Location
cd $sqlpsPath
update-FormatData -prependpath SQLProvider.Format.ps1xml
Pop-Location  


I have wrapped it in the Function Load-SQLSMO {} clause so I could use the code as a function.

I've tried to use the try...catch...finally block, but it seems like I did it incorrectly:

#
# Loads the SQL Server Management Objects (SMO)
#

$ErrorActionPreference = "Stop"

$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

try {
 Get-ChildItem $sqlpsreg
}

catch {

    throw "SQL Server Provider for Windows PowerShell is not installed."

}

finally

{
    $item = Get-ItemProperty $sqlpsreg
    $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)

}

$assemblylist =
"Microsoft.SqlServer.Management.Common","Microsoft.SqlServer.Smo","Microsoft.SqlServer.Dmf ","Microsoft.SqlServer.Instapi ","Microsoft.SqlServer.SqlWmiManagement ","Microsoft.SqlServer.ConnectionInfo ","Microsoft.SqlServer.SmoExtended ","Microsoft.SqlServer.SqlTDiagM ","Microsoft.SqlServer.SString ","Microsoft.SqlServer.Management.RegisteredServers ","Microsoft.SqlServer.Management.Sdk.Sfc ","Microsoft.SqlServer.SqlEnum ","Microsoft.SqlServer.RegSvrEnum ","Microsoft.SqlServer.WmiEnum ","Microsoft.SqlServer.ServiceBrokerEnum ","Microsoft.SqlServer.ConnectionInfoExtended ","Microsoft.SqlServer.Management.Collector ","Microsoft.SqlServer.Management.CollectorEnum","Microsoft.SqlServer.Management.Dac","Microsoft.SqlServer.Management.DacEnum","Microsoft.SqlServer.Management.Utility"

foreach ($asm in $assemblylist)
{
    $asm = [Reflection.Assembly]::LoadWithPartialName($asm)
}

Push-Location
cd $sqlpsPath
update-FormatData -prependpath SQLProvider.Format.ps1xml
Pop-Location  

The code still doesn't throw the provided error. Looks like PowerShell handles it _before_ the code gets the chance to throw the error message.

Could somebody please explain what's wrong with original code, and if nothing is wrong, how it is supposed to get the custom error thrown?

Thank you.


Well this is the world we live in And these are the hands we're given...


how to add a standard printer port using Powershell WMI.

$
0
0

Hi guys, I am trying to add a standard printer port using powershell as follows :-

Function CreatePrinterPort {
param ($PrinterIP, $PrinterPort, $PrinterPortName, $ComputerName)
$wmi = [wmiclass]”\\$ComputerName\root\cimv2:win32_tcpipPrinterPort”
$wmi.psbase.scope.options.enablePrivileges = $true
$Port = $wmi.createInstance()
$Port.name = $PrinterPortName
$Port.hostAddress = $PrinterIP
$Port.portNumber = $PrinterPort
$Port.SNMPEnabled = $false
$Port.Protocol = 1
$Port.put()
}

The problem I have is I want to add an LPR port not a standard TCP/IP port. the above script creates a port in the registry under \Print\Monitors\Standard TCP/IP port\

but I need the port creating under \Print\Monitors\LPR port.

is there any way I can do this ?

Thanks

Mark Green

 

Migration Script Issue - Please help

$
0
0
wscript.echo "**********************************************************"
wscript.echo "**********************************************************"
wscript.echo "Script Name :  SBC_CitrixUSerFMOMigration.vbs [SIMULATED | DOIT]"
wscript.echo "Description : "
wscript.echo "   This takes VIA Userids (in users.txt) and..."
wscript.echo "   a) removes the ID from each group listed in Col 1"
wscript.echo "   b) adds    the ID to   each group listed in Col 2"
wscript.echo "   of groups.txt "
wscript.echo "   The parameter SIMULATED will report only"
wscript.echo "   The parameter DOIT will make changes"
wscript.echo ""
wscript.echo "Files input ..."
wscript.echo "  users.txt ...must contain a list of RACFIDs"
wscript.echo "  groups.txt...must contain groupName1<TAB>groupName2"
wscript.echo ""
wscript.echo "Clauses..."
wscript.echo "  1/ Not Supported by members of the Directory services Team"
wscript.echo "  2/ Supplied without warranty, use at your own risk"
wscript.echo "  3/ Not fully tested, No incidents will be accepted into "
wscript.echo "     the HP directory services Q as a result of this script"
wscript.echo "   4/ Nested groups has NOT been catered for"
wscript.echo "**********************************************************"
wscript.echo "**********************************************************"

set objArgs=wscript.Arguments
if objArgs.Count =1 then
	param1=objArgs(0)
else
	call Helpp
end if
if param1="DOIT" then
	SIMULATED="FALSE"
else
	SIMULATED="TRUE"
end if

wscript.echo "Script Start : " & now

tempcount=0

'Option Explicit
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1,  TristateFalse = 0
const ADS_SCOPE_SUBTREE  = 2

Const E_ADS_PROPERTY_NOT_FOUND  = &h8000500D


Dim objConnection, objCommand, objRootDSE, strDNSDomain, strQuery
Dim objRecordSet, strDN, objGroup
dim objects_in_group
dim objargs, member_threshold, group_count, dummy, countt
dim subgroup,Str_tabs,loop_,Strdescription

dim Racfids()

dim TempUserGroup()
redim TempUserGroup(0)

dim TempUserGroupAdd()
redim TempUserGroupAdd(0)



dim groups1()
redim groups1(0)

dim groups2()
redim groups2(0)


dim strFileName
dim objFSO
dim objFile
dim strLine
dim pos
dim x


objects_in_group=0
group_count=0
subgroup=0
Str_tabs=""



wscript.echo "Loading groups..."
'load into Racfids array
strFileName = "groups.txt"
x=0
grp_errors=0
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)', True, TristateFalse )
	While not objFile.AtEndOfStream
		strLine = UCASE(objFile.ReadLine)
		x=x+1
		if trim(strLine) <>"" then 'ignore blank lines
			pos=instr(strLine,chr(9))
			if pos >1 then 'must contain one tabsepartor not col 1
				redim preserve groups1(ubound(groups1)+1)
				groups1(ubound(groups1))=mid(trim(strLine),1,pos-1)

				redim preserve groups2(ubound(groups2)+1)
				groups2(ubound(groups2))=mid(trim(strLine),pos+1)
			else
				wscript.echo "Error in file format groups.txt...Please correct Line :" & x
				grp_errors=grp_errors+1
			end if
		end if
		'pos=instr(strLine,chr(9))

    wend
objFile.Close
wscript.echo "Loading groups...Done"


if grp_errors>0 then
	wscript.echo "Please correct groups.txt and re-run"
	wscript.echo "[NB group.txt format is  ...   groupName1<TAB>groupName2"
	wscript.quit
end if




wscript.echo "Loading RACFIDS..."
'load into Racfids array
redim Racfids(0)

strFileName = "users.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)', True, TristateFalse )
	While not objFile.AtEndOfStream
		strLine = UCASE(objFile.ReadLine)
		if strLIne <>"" then
			redim preserve Racfids(ubound(Racfids)+1)
			Racfids(ubound(Racfids))=trim(strLine)
			'wscript.echo "users.txt" & VBTAB & strLine
		end if
    wend
objFile.Close
wscript.echo "Loading RACFIDS...Done"



WSCRIPT.ECHO "==============Checking Groups.txt for existance in AD======================="
grp_errors=0
for x = 1 to  UBOUND (groups1)
	bit=""
	wscript.echo x & VBTAB &  ":" & groups1(x) & ":" & groups2(x) & ":"
	bit=GetDN(groups1(x))
	if bit="" then
		wscript.echo "FATAL Error. AD Group does not exist whichis present in groups.txt :" & groups1(x)
		grp_errors=grp_errors+1
	else
		groups1(x)=UCASE(bit)
	end if
	bit=""
	bit=GetDN(groups2(x))
	if bit="" then
		wscript.echo "FATAL Error. AD Group does not exist whichis present in groups.txt :" & groups2(x)
		grp_errors=grp_errors+1
	else
		groups2(x)=UCASE(bit)
	end if
	'StrName can be a group or user
next
if grp_errors>0 then
	wscript.echo "Please correct groups.txt and re-run"
	wscript.quit
end if
WSCRIPT.ECHO "============Group check Complete============================"

WSCRIPT.ECHO "======Processing users.txt==================================="
for x = 1 to  UBOUND (Racfids)
	UserDN=GetDN(Racfids(x))
	UserDN=UCASE(UserDN)
	if UserDN<>"" then
		wscript.echo
		wscript.echo x & VBTAB &  ":" & Racfids(x) & ":"		& VBTAB & UserDN
		wscript.echo VBTAB &  "Current group Membership [that matches col 1 in groups.txt]"
		call ListUserGroups(Racfids(x))

		wscript.echo VBCRLF & VBTAB &  "Groups Needing removal..."
		if UBOUND(TempUserGroup)=0 then wscript.echo VBTAB & "None"
		call display_array(TempUserGroup)	'tempusergroup array should now be loaded and only contain groups which are in teh first column of groups1.txt

		wscript.echo VBCRLF & VBTAB &  "Groups Needing Adding..."
		if UBOUND(TempUserGroupAdd)=0 then wscript.echo VBTAB & "None"
		call display_array(TempUserGroupAdd)	'tempusergroup array should now be loaded and only contain groups which are in teh second column of groups1.txt
		call process_user(UserDN)		'go thru each group in array and add and remove
	else
		wscript.echo x & VBTAB &  ":" & Racfids(x) & ":"		& VBTAB & "ERROR : NOSUCH USER"
	end if
	call Clear_Array(TempUserGroup) 'this is a temp working array containing users group membership listin DN form
	call Clear_Array(TempUserGroupAdd) 'this is a temp working array containing users group membership listin DN form

next
WSCRIPT.ECHO "========End processing users.txt =============================="




wscript.echo "Script End : " & now
wscript.quit



function process_user(strUserDN)		'go thru each group in array and add and remove
	dim p
	for p= 1 to UBOUND(TempUserGroup)

		wscript.echo ""
		result=RemoveUserFromGroup(TempUserGroup(p),strUserDN)

		if IsInGroup(strUserDN,TempUserGroup(p))="FALSE" OR SIMULATED="TRUE" then  'it it worked
			result=AddUserToGroup(TempUserGroupAdd(p),strUserDN)
			if IsInGroup(strUserDN,TempUserGroupAdd(p))="TRUE" OR SIMULATED="TRUE" then  'it it worked
				'do nothing as all ok
			else
				'user not in group so backout change
				result=AddUserToGroup(TempUserGroup(p),strUserDN)
				if IsInGroup(strUserDN,TempUserGroup(p))="TRUE" then  'backout worked
					wscript.echo VBTAB & "Backout worked, user is back in original group"
				else
					wscript.echo VBTAB & "ERROR : Backout did NOT work, user must be changed manually"
				end if
			end if
		else
			'wscript.echo "ERROR Unable to remove user from group"
		end if


		'we did not add user OK, so we must try backout
		'if AddUserToGroup(TempUserGroup(p),strUserDN)="OK" then



	next
end function



function ShortDN(StrName)
	on error resume next
	dim result,pos
	result=""
	pos=instr(StrName,",")
	result=mid(StrName,4,pos-4)

	on error goto 0
	ShortDN=result
end function



function RemoveUserFromGroup(strGroupDN,strMemberDN)
	dim objGroup,result
	'strGroupDN = "<GroupDN>"  ' e.g. cn=SalesGroup,ou=Groups,dc=rallencorp,dc=com
	'strMemberDN = "<MemberDN>" ' e.g. cn=jsmith,cn=users,dc=rallencorp,dc=com
	' ------ END CONFIGURATION ---------
	RemoveUserFromGroup="FALSE"
	Err.Clear
	on error resume next
		set objGroup = GetObject("LDAP://UKNWDAVIA811.via.novonet/" & strGroupDN)
		'ldp="'LDAP://UKNWDAVIA811.via.novonet/dc=via,dc=novonet'"
		' Remove a member
		if SIMULATED="FALSE" then
			wscript.Echo VBTAB & "Removing user from   : " &  ShortDN(strGroupDN)
			objGroup.Remove("LDAP://" & strMemberDN)
			result=Err.Number
			if result =-2147016651 then 'user already removed
				RemoveUserFromGroup="OK"
				wscript.Echo VBTAB & "Warning : User already removed from group : " & ShortDN(strGroupDN)
			else
				if result<>0 then
					wscript.Echo VBTAB & "ERROR : " & Err.Number & " removing user from group : " & ShortDN(strGroupDN)
				else
					RemoveUserFromGroup="OK"
				end if
			end if
		else
			wscript.Echo VBTAB & "Simulated : Removing user from : " &  ShortDN(strGroupDN)
		end if

	on error goto 0
end function

function AddUserToGroup(strGroupDN,strMemberDN)
	dim objGroup
	'strGroupDN = "<GroupDN>"  ' e.g. cn=SalesGroup,ou=Groups,dc=rallencorp,dc=com
	'strMemberDN = "<MemberDN>" ' e.g. cn=jsmith,cn=users,dc=rallencorp,dc=com
	' ------ END CONFIGURATION ---------
	AddUserToGroup="FALSE"
	Err.Clear
	on error resume next
		set objGroup = GetObject("LDAP://UKNWDAVIA811.via.novonet/" & strGroupDN)
		' Remove a member
		if SIMULATED="FALSE" then
			wscript.Echo VBTAB & "Adding user to group : " & ShortDN(strGroupDN)
			objGroup.Add("LDAP://" & strMemberDN)
			result=Err.Number
			if result=-2147019886 then 'user already in group
				AddUserToGroup="OK"
				wscript.Echo VBTAB & "Warning : User already in group : " & ShortDN(strGroupDN)
			else
				if result<>0 then
					wscript.Echo VBTAB & "ERROR : " & Err.Number & " Adding user to group : " & ShortDN(strGroupDN)
					'wscript.Echo "Removing ...:" & strMemberDN
					'remove_count=remove_count+1
				else
					AddUserToGroup="OK"
				end if
			end if
		else
			wscript.Echo VBTAB & "Simulated : Adding user to group : " & ShortDN(strGroupDN)
		end if
	on error goto 0
end function





function Get_Domain()	'gets the default domain name
	Set objDomain = getObject("LDAP://rootDse")
	objDC = objDomain.Get("DefaultNamingContext")
	DC=mid(objDC,1,instr(objDC,",")-1)
	Get_Domain=mid(DC,4)
end function


'wscript.echo "Start Script..."
'StrComputer="."
'set ObjUser=GetObject("WinNT://via.novonet/fred,user")

'set ObjGroup=GetObject("WinNT://" & StrComputer & "/Administrators,Group")

'ObjGroup.Add (ObjUser.ADsPath)

'wscript.echo "End Script..."


function local_computer_name
	strComputer = "."
	Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
	Set colSettings = objWMIService.ExecQuery ("Select * from Win32_ComputerSystem")
		For Each objComputer in colSettings
		Wscript.Echo "System Name: " & objComputer.Name
		local_computer_name=objComputer.Name
	Next
end function


function display_array(Arr)
	wscript.Echo
	'wscript.Echo "Array..."
	for loop_ =1 to UBOUND(arr)
		wscript.Echo VBTAB & loop_ & TAB & ":" & arr(loop_)	&":"
	next
	'wscript.Echo "Array end."
	wscript.Echo
end function

function get_local_admins(strComputer)
	dim strDomain, objWshNetwork, strGroupSID, strGroupName, objGroup, objMember
	dim bit, pos, strObject

	Set objWshNetwork = CreateObject("WScript.Network")
	'strComputer = objWshNetwork.ComputerName
	strGroupSID = "S-1-5-32-544" ' Well Known SID of the Administrators group

	' Obtain the group name based on well know SID
	strGroupName = GetGroupName(strComputer, strGroupSID)

	' Connect to the group
	Err.Clear
	on error resume next
	Set objGroup = GetObject("WinNT://" & strComputer & "/" & strGroupName & ",group")
	if Err.Number <> 0 then
		wscript.echo VBTAB & "Error Connecting..." & VBTAB & Err.Number & VBTAB & Err.Description
	else
		on error goto 0
		' Display all member names in the group
		For Each objMember in objGroup.Members
			'redim preserve ArrLocalMembers(UBOUND(ArrLocalMembers)+1)
			'WScript.Echo vbtab & "Members....:" & objMember.Name & ".........adspath....: " & objMember.AdsPath
			if instr(objMember.AdsPath,strComputer) >0 then 'must be a local computer object
				wscript.echo VBTAB & strComputer & "\" & objMember.Name & " [" & RacfidLookup(objMember.Name) &"]"
			else	'must be a domain object
				'wscript.echo "AdsPath:" & objMember.AdsPath & ":"

					'ignore first WinNT://

					bit=mid(objMember.AdsPath,9)
					'wscript.echo VBTAB & "Domain Lookup drill down group members...."&  bit
					pos=instr(bit,"/")
					if pos=0 then
						wscript.echo VBTAB & "Warning : Possible unresolved SID [" & objMember.AdsPath & "] needs tidying in Local Admin on :" & strComputer
					else
						strDomain=mid(bit,1,pos-1)
						strObject=mid(bit,pos+1)
						call GetDomainUsers(strDomain,strObject)
							'wscript.echo VBTAB & bit & " [" & RacfidLookup(strObject) &"]"
							'lookup domain users DN
						'end if
					end if
			end if
		Next
	end if

	on error goto 0

end function


Function GetGroupName(sComputer, sGroupSID)
	' List of well know SID's is available here:
	'
	' Well-known security identifiers in Windows operating systems
	' http://support.microsoft.com/?id=243330
	on error resume next
	Dim oGroupAccounts, oGroupAccount

	Set oGroupAccounts = GetObject("winmgmts://" & sComputer & "/root/cimv2") _
	.ExecQuery("Select Name from Win32_Group" & " WHERE Domain = '" & sComputer & "' AND SID = '" & sGroupSID & "'")

	if Err.Number <> 0 then
			wscript.echo VBTAB & "Error Connecting..." & VBTAB & Err.Number & VBTAB & Err.Description
	else
		If oGroupAccounts.Count = 0 Then
			' need to use Domain = 'BUILTIN' at least for Win2k SP2
			Set oGroupAccounts = GetObject( "winmgmts://" & sComputer & "/root/cimv2") _
			 .ExecQuery("Select Name from Win32_Group" & " WHERE Domain = 'BUILTIN' AND SID = '" & sGroupSID & "'")
		End If

		For Each oGroupAccount In oGroupAccounts
			GetGroupName = oGroupAccount.Name
		Next
	end if
	on error goto 0
End Function



function RacfidLookup(StrName)
	dim retval
	dim searchtxt
	dim x

	retval=""
	searchtxt=UCASE(StrName)
	for x = 1 to ubound(Racfids)
		if searchtxt=Racfids(x) then
			retval=RacfidsDesc(x)
			exit for
		end if
	next
	if retval="" then retval="RACFID not found"
	RacfidLookup=retval
end function



function Notused_GetDNDomainUsers(strDomain,strObject)

	if strDomain ="AVIVAGROUP" then
		ldp="'LDAP://UKNCDAVIA001.avivagroup.com/dc=avivagroup,dc=com'"
	else
		if strDomain ="VIA" then
			ldp="'LDAP://UKNWDAVIA811.via.novonet/dc=via,dc=novonet'"
		else
			if strDomain ="ECS" then
				ldp="'LDAP://UKNCDAVIA101.ecs.com/dc=ecs,dc=com'"
			else
				wscript.echo "ERROR. NEw Domain:" & "PArameters...Domain & object:" & strDomain & ":" & strObject
				exit function
			end if
		end if
	end if


end function



Function GetType(intType)
' Function to determine group type from the GroupType attribute.
  If (intType And &h01) <> 0 Then
    GetType = "Built-in"
  ElseIf (intType And &h02) <> 0 Then
    GetType = "Global"
  ElseIf (intType And &h04) <> 0 Then
    GetType = "Local"
  ElseIf (intType And &h08) <> 0 Then
    GetType = "Universal"
  End If
  If (intType And &h80000000) <> 0 Then
    GetType = GetType & "/Security"
  Else
    GetType = GetType & "/Distribution"
  End If
End Function

Sub GetMembers(objADObject)
' Subroutine to document group membership.
' Members can be users or groups.
  Dim objMember, strType
  'wscript.echo "TASK GROUP..." & objADObject.name
  subgroup=subgroup+1
  'group_enumerated=FALSE

  Err.Clear
  on error resume next
  For Each objMember In objADObject.Members
	if Err.Number <>0 then exit for
    Str_tabs=""
    for loop_=1 to subgroup
     	Str_tabs=Str_tabs & "             "
    next

    If UCase(Left(objMember.objectCategory, 8)) = "CN=GROUP" Then
      'group_enumerated=TRUE
      strType = "Group"
      objects_in_group=objects_in_group+1
      GetType(objGroup.groupType)
      wscript.echo Str_tabs & "Contains...: " & objMember.sAMAccountName & " (" & strType & ")" & VBTAB & "[" & GetType(objGroup.groupType) & "] " & objMember.description
      call GetMembers(objMember)
      subgroup=subgroup-1
      'wscript.Echo "Objects in group...:" & objects_in_group
    Else
      'strType = "User_or_computer"
      objects_in_group=objects_in_group+1
      if objMember.sAMAccountName="" then
      	wscript.Echo Str_tabs & "Contains...: " & "Errr...Possible foreign security principle....have not worked out how to get friendly name yet!....SID :" & ":" & objMember.Name
      else
      	wscript.echo Str_tabs & "Contains...: " & objMember.sAMAccountName & " (" & RacfidLookup(objMember.sAMAccountName) & ")      " & NiceDN(objMember.distinguishedName)
      end if
    End If
  Next

  	on error goto 0


  'Set objMember = Nothing
End Sub




function NiceDN(SStrDN)
	'CN=xxxxx,OU=GRPTAX,OU=ACO,OU=User Accounts,DC=VIA,DC=NOVONET
	'wscript.Echo "StrDN:" & StrDN
	arr=split(SStrDN,",")
	for loop_=UBOUND(arr)-2 to 1 step -1
		'wscript.Echo "loop:" & loop_
		NiceDN=NiceDN & "\" & mid(arr(loop_),4)
	next
	NiceDN= NiceDN
end function


Function IsGroup(strDN)
	dim objGroup, intgroupType, retval

	Set objGroup = GetObject   ("LDAP://" & strDN)
	objGroup.GetInfo
	Err.Clear
	On error resume next
		descr=""
		descr = objGroup.Get("description")
		Err.Clear
		intgroupType = objGroup.Get("groupType")
		if Err.Number <> 0 then
			retval="FALSE"
			'wscript.echo "FALSE" & descr
			'wscript.echo "DN:" & strDN
		else
			retval=descr
			'wscript.echo "TRUE" &retval
		end if
	on error goto 0
	IsGroup=retval

end function




Function FindComputerObject(strComputer)
	dim ldp, result
	strComputer=Trim(strComputer)


    ldp="SELECT Name, distinguishedName, operatingSystem, operatingSystemVersion, operatingsystemservicepack FROM 'LDAP://UKNWDAVIA101.ecs.com/DC=ECS,DC=com' WHERE objectCategory='computer' and Name='"  & strComputer  & "'"
    result = Main (ldp,"ecs.com")

	if result="NotFound" then
		ldp="SELECT Name, distinguishedName, operatingSystem, operatingSystemVersion, operatingsystemservicepack FROM 'LDAP://UKNWDAVIA811.VIA.NOVONET/DC=VIA,DC=NOVONET' WHERE objectCategory='computer' and Name='"  & strComputer  & "'"
		result = Main (ldp,"via.novonet")
		if result="NotFound" then
			ldp="SELECT Name, distinguishedName, operatingSystem, operatingSystemVersion, operatingsystemservicepack FROM 'LDAP://UKNCDAVIA001.avivagroup.com/dc=avivagroup,dc=com' WHERE objectCategory='computer' and Name='"  & strComputer  & "'"
			result = Main (ldp,"avivagroup.com")
			if result="NotFound" then
				FindComputerObject = strComputer & " Not Found"
			end if
		end if
	end if
	FindComputerObject = result
end function


function Main(SQL,StrDomain)
	dim objConnection9, objCommand9, objRecordSet9, res, count, Name, bit
	dim DN,pos, OS, OSver ,	OSsp
	'wscript.echo SQL

	Set objConnection9 = CreateObject("ADODB.Connection")
	Set objCommand9 = CreateObject("ADODB.Command")
	objConnection9.Provider = ("ADsDSOObject")
	objConnection9.Open "Active Directory Provider"
	objCommand9.ActiveConnection = objConnection9
	objCommand9.Properties("Page Size") = 1000
	objCommand9.Properties("Searchscope") = ADS_SCOPE_SUBTREE

	'SQL="SELECT Name, distinguishedName, operatingSystem, operatingSystemVersion, operatingsystemservicepack FROM 'LDAP://UKNWDAVIA811.VIA.NOVONET/DC=VIA,DC=NOVONET' WHERE objectCategory='computer' and Name='"  & strComputer  & "'"
	'SQL="SELECT Name FROM 'LDAP://UKNWDAVIA811.VIA.NOVONET/DC=VIA,DC=NOVONET' WHERE Name='UKNCSAVIA008'"
	objCommand9.CommandText = SQL

	'wscript.echo SQL

	Set objRecordSet9 = objCommand9.Execute

	on error resume next
		objRecordSet9.MoveFirst
		res="NotFound"
	on error goto 0

	Do Until objRecordSet9.EOF
		'wscript.echo "Hereeeee"
		Name= objRecordSet9.Fields("Name").Value
		bit=mid(Name,1,2)
		if UCASE(bit)="VW" or UCASE(bit)="LT" or UCASE(bit)="WS" or UCASE(bit)="TB" or UCASE(bit)="DR" then
			'ignore
		else
			count=count +1
			DN    =  objRecordSet9.Fields("distinguishedName").Value
			pos = instr(DN,",")
			DN =  mid(DN,pos+1)
			OS    =  objRecordSet9.Fields("operatingSystem").Value
			OSver =  objRecordSet9.Fields("operatingSystemVersion").Value
			OSsp = objRecordSet9.Fields("operatingsystemservicepack").Value
			res= Name & "." & StrDomain & VBTAB & NiceDN(objRecordSet9.Fields("distinguishedName").Value) & VBTAB & OS & VBTAB & OSver & VBTAB & OSsp

		end if
		objRecordSet9.MoveNext
		'if count >1000 then exit do
	Loop
	'wscript.echo "Total : " & count
	Main=res
end function



function IsInGroup(userDN,strGroupDN)
	dim objGroup
	'only goes first layer down for nexted groups
	'this is very slow
	set objGroup = GetObject("LDAP://UKNWDAVIA811.via.novonet/" & strGroupDN)

	ingroup="FALSE"
	for each objMember in objGroup.Members
		'wscript.Echo "Is USER...:" & userDN
		'wscript.echo "in group  :" & strGroupDN
		'wscript.echo "    DN:" & objMember.distinguishedName
		'wscript.echo "UserDN:" & userDN
   		if UCASE(objMember.distinguishedName) = userDN then
   			ingroup="TRUE"
   			exit for
   		end if
  	next
   	IsInGroup=ingroup
end function

Function NOTUSEDIsInGroup(userDN,groupName)
	dim Username
	Username=ShortDN(userDN)
     If IsEmpty(groupListD) then
		Set groupListD = CreateObject("Scripting.Dictionary")
		groupListD.CompareMode = TextCompare
        'ADSPath = EnvString("userdomain") & "/" & EnvString("username")
		Set userPath = GetObject("WinNT://" & "UKNWDAVIA811.via.novonet/" & Username & ",user")
		For Each listGroup in userPath.Groups
			groupListD.Add listGroup.Name, "-"
		Next
	End if
	IsInGroup = CBool(groupListD.Exists(groupName))
End Function












function GetDN(StrName) 'StrName can be a group or user
	'On Error Resume Next
	dim objConnection2,objCommand2,objUser2,objRecordSet2,strDN2
	strDN2=""
	Const ADS_SCOPE_SUBTREE = 2

	Set objConnection2 = CreateObject("ADODB.Connection")
	Set objCommand2 =   CreateObject("ADODB.Command")
	objConnection2.Provider = "ADsDSOObject"
	objConnection2.Open "Active Directory Provider"
	Set objCommand2.ActiveConnection = objConnection2

	objCommand2.Properties("Page Size") = 1000
	objCommand2.Properties("Searchscope") = ADS_SCOPE_SUBTREE

	objCommand2.CommandText = _
		"SELECT distinguishedName FROM 'LDAP://dc=VIA,dc=NOVONET' WHERE objectCategory='user' " & _"AND sAMAccountName = '" & StrName & "'"

	strQuery="Select Name,distinguishedName,objectclass from 'LDAP://UKNWDAVIA811.via.novonet/dc=VIA,dc=NOVONET' where objectClass='group' and ( Name ='" & StrName & "') OR objectCategory='user' and ( sAMAccountNAme ='" & StrName & "') "
	'"LDAP://UKNWDAVIA811.via.novonet/" &   trbhere
	objCommand2.CommandText = strQuery


	Set objRecordSet2 = objCommand2.Execute

	If objRecordSet2.EOF Then
		'Wscript.Echo "WARNING : No objects found for " & objCommand2.CommandText
	else
		objRecordSet2.MoveFirst
		Do Until objRecordSet2.EOF
			strDN2 = objRecordSet2.Fields("distinguishedName").Value
			objRecordSet2.MoveNext
		Loop
	end if

	'Set objUser = GetObject("LDAP://" & strDN)
	'Wscript.Echo objUser.Name
	GetDN=strDN2
end function


function ListUserGroups(strUserDN)

	DN=GetDN(strUserDN)
	if DN="" then
		ListUserGroups=""
		wscript.Echo VBTAB & "ERROR : no such user"
		call Clear_Array(TempUserGroup)
		exit function
	end if
	Set objUser = GetObject     ("LDAP://UKNWDAVIA811.via.novonet/"  & DN)
	intPrimaryGroupID = objUser.Get("primaryGroupID")
	arrMemberOf = objUser.GetEx("memberOf")
	If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
	    WScript.Echo VBTAB & strUserDN & "The memberOf attribute is not set...ie no groups"
	Else
	    For each Group in arrMemberOf
			call AddToArrays(UCASE(Group))
	    Next
	End If

	'below gets the name of primary group from token
	Set objConnection = CreateObject("ADODB.Connection")
	objConnection.Open "Provider=ADsDSOObject;"
	Set objCommand = CreateObject("ADODB.Command")
	objCommand.ActiveConnection = objConnection
	'objCommand.CommandText =   "<LDAP://dc=VIA,dc=NOVONET>;(objectCategory=Group);" &   "distinguishedName,primaryGroupToken;subtree"
	objCommand.CommandText =   "<LDAP://UKNWDAVIA811.via.novonet/dc=VIA,dc=NOVONET>;(objectCategory=Group);" &   "distinguishedName,primaryGroupToken;subtree"

	Set objRecordSet = objCommand.Execute

	bit=""
	on error resume next
	While Not objRecordset.EOF
	    If objRecordset.Fields("primaryGroupToken") = intPrimaryGroupID Then
	        'WScript.Echo VBTAB & "Primary group:"
			bit=objRecordset.Fields("distinguishedName")
			if bit <>"" then call AddToArrays(UCASE(bit))
	    End If
	    objRecordset.MoveNext
	Wend
	objConnection.Close
	on error goto 0
end function



function Clear_Array(arr)
	redim arr(0)
end function


function notusedIsInArray2(searchtxt)  'searchtxt is a DN
	wscript.echo "searchtxt:" & searchtxt & ":"
	dim l
	IsInArray2=0
	for l = 1 to UBOUND(groups1)
		wscript.echo "groups1(l):" & groups1(l) & ":"
		if searchtxt=groups1(l) then
			IsInArray2=l
			exit function
		end if
	next

end function



function NOTUSEDIsInArray(searchtxt)  'searchtxt is a DN
	dim l
	dim res
	res=-1
	'wscript.echo "isinarr searchtxt :" &searchtxt
	for l = 1 to UBOUND(groups1)
		'wscript.echo "isinarr groups1 :" & l & VBTAB & groups1(l)
		if instr(searchtxt, groups1(l))=4 then
			res=l
			exit for
		end if
	next
	if res=-1 then
		'wscript.echo "isinarr Not FOUND"
	else
		'wscript.echo "isinarr FOUND at : " & res
	end if
	IsInArray=res
end function


function AddToArrays(StrTxt)
	dim l
	dim res,bit

	tempcount=tempcount+1
	'wscript.echo tempcount & VBTAB & "StrTxt :" & StrTxt &":"
	for l = 1 to UBOUND(groups1)
		'wscript.echo "Groups1 :" & l & VBTAB & ":" &  groups1(l) &":"

		if groups1(l)=StrTxt then
			redim preserve TempUserGroupAdd(UBOUND(TempUserGroupAdd)+1)
			TempUserGroupAdd(ubound(TempUserGroupAdd))=groups2(l)

			redim preserve TempUserGroup(UBOUND(TempUserGroup)+1)
			TempUserGroup(ubound(TempUserGroup))=UCASE(StrTxt)
			'wscript.Echo "FFFFOUND" & VBTAB & UBOUND(TempUserGroup) &" " & groups1(l)
			'exit for
		end if
	next
	'if res=-1 then
		'wscript.echo "isinarr Not FOUND"
	'else
		'wscript.echo "isinarr FOUND at : " & res
	'end if
end function




function Helpp
	wscript.echo "ERROR : Parameter 1 missing"
	wscript.quit
end function




'SIMULATED="FALSE"
'usr="CN=TTBURROUT,OU=DIRECTORY SERVICES,OU=HP ENTERPRISE SERVICES,OU=NUCS,OU=USER ACCOUNTS,DC=VIA,DC=NOVONET"
'ggroup="CN=SBC_ROL_LIVE_LIFE_ADMINRE06,OU=USER ROLES,OU=CITRIX GROUPS,OU=APP DELEGATION,OU=SECURITY,OU=GROUPS,DC=VIA,DC=NOVONET"
'call RemoveUserFromgroup(ggroup,usr)


'usr="CN=TTBURROUT,OU=DIRECTORY SERVICES,OU=HP ENTERPRISE SERVICES,OU=NUCS,OU=USER ACCOUNTS,DC=VIA,DC=NOVONET"
'ggroup="CN=SBC_ROL_LIVE_LIFE_ADMINRE06,OU=USER ROLES,OU=CITRIX GROUPS,OU=APP DELEGATION,OU=SECURITY,OU=GROUPS,DC=VIA,DC=NOVONET"
'call RemoveUserFromgroup(ggroup,usr)


'SIMULATED="FALSE"
'usr="CN=TTBURROUT,OU=DIRECTORY SERVICES,OU=HP ENTERPRISE SERVICES,OU=NUCS,OU=USER ACCOUNTS,DC=VIA,DC=NOVONET"
'ggroup="CN=SBC_ROL_LIVE_LIFE_ADMINRE06,OU=USER ROLES,OU=CITRIX GROUPS,OU=APP DELEGATION,OU=SECURITY,OU=GROUPS,DC=VIA,DC=NOVONET"
'call AddUserToGroup(ggroup,usr)


'usr="CN=TTBURROUT,OU=DIRECTORY SERVICES,OU=HP ENTERPRISE SERVICES,OU=NUCS,OU=USER ACCOUNTS,DC=VIA,DC=NOVONET"
'ggroup="CN=SBC_ROL_LIVE_LIFE_ADMINRE06,OU=USER ROLES,OU=CITRIX GROUPS,OU=APP DELEGATION,OU=SECURITY,OU=GROUPS,DC=VIA,DC=NOVONET"
'call AddUserToGroup(ggroup,usr)

'wscript.quit



The below script is not working from windows 2003 to windows 2008.

  • VBScript used on windows ENV to migrate the users.
  • The script was run on a Windows 2003 machine.
  • Now it has compatible issues in running on Windows 2008 server.
  • The script was last run some 4-5 months back on 2008 server and it failed, now we do not have any

windows 2003 servers.

  • The requirement out here is to come up with a script or, windows PowerShell scripting or, any other mean to migrate the users.

Bug in Get-PSCallStack

$
0
0

It reports some non-null parameters as $null.

PS C:\> function foo { Get-PSCallStack }

PS C:\> foo -2 -1 0 1 2

Command       Arguments             Location        
-------       ---------             --------        
foo           {-2, -1, $null, 1, 2} Test.ps1: line 2
<ScriptBlock> {}                    <No file>       

PS C:\> foo $true $false

Command       Arguments     Location        
-------       ---------     --------        
foo           {True, $null} Test.ps1: line 2
<ScriptBlock> {}            <No file>       

# My environment:

PS C:\> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      14393  187     


Exception calling "Put".... when assigning a drive letter?

$
0
0

I have a script I am writing to replace some old SMS scripting for assigning drive letters on machines when applying a new image through SCCM 2007 OSD Task Sequencing. Everything is working, and all drive letters are being assigned properly except for S:.  I receive the following error for that drive:

 Exception calling "Put" with "0" argument(s): "Not available "

The volume labels are assigned during the imaging process, and the script runs upon the first boot to the OS.  This is on Powershell v3 (we can't move higher due to some conflicts in our current OS build).  Below is the script

if(get-wmiobject win32_cdromdrive)

{$driveD = Get-WmiObject win32_volume -filter "DriveType = 5"

$driveD.driveletter = 'D:'

$driveD.put()

}

$driveC = Get-WmiObject win32_volume -Filter "Label = 'Default'"

$driveC.DriveLetter = 'C:'

$driveC.put()

$driveT = Get-WmiObject win32_volume -Filter "Label = 'Thaw'"

$driveT.DriveLetter = 'T:'

$driveT.put()

$driveS = Get-WmiObject win32_volume -Filter "Label = 'TLTDisk'"

$driveS.DriveLetter = 'S:'

$driveS.put()

Creating an array from the registry.

$
0
0

Hi Guys,

I have a strange need to recurse and number a registry location to assist SCCM in elevating network configurations.  I've written out this - 

$adapterarray = Get-Childitem -path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards" -recurse | foreach {Get-ItemProperty -Path $_.pspath}


But when I run a foreach on it to display names, the strings come out as -

@{Description=Realtek PCIe GBE Family Controller}

So then I decided to attempt to just create a new object with just the properties I need in the correct string format I want with this -

Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards" -recurse | foreach {
                    $displayname = (Get-ItemProperty -Path $_.pspath).description | Out-String
                    $servicename = (Get-ItemProperty -Path $_.pspath).ServiceName | Out-String
                    $object = New-Object System.Object
                    $object | Add-Member -TypeName NoteProperty -Name Name -value $displayname
                    $object | Add-Member -TypeName NoteProperty -Name GUID -value $servicename
                    $adapterarray += $object


}

And that poops the bed.  Anyone that might be able to lead me in the right direction?  The end result is that I want this to display the names of the cards, and then run start ::{208D2C60-3AEA-1069-A2D7-08002B30309D}\::{7007ACC7-3202-11D1-AAD2-00805FC1270E}\::CARDGUIDHERE to pop the network card configuration open... but if I can't properly enumerate an array from the registry with just the values I can't get to where I can run that command.  I know this sounds complex but it's a strict environment and there's a need to configure network cards to access onsite off-network devices and they will not have admin.  Thanks.

Ryan


Try and Catch not working

$
0
0

The script at the bottom is to read active servers from AD and get software inventory from them.     Then write out to a CSV.    All that works as expected, but my catch is not executing when there is an error.    I get one of these errors instead of the name of the failed server outputted to the  screen every time it can't get to a server.  Any ideas?


Header on error:

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)


Script:


import-module activedirectory 
$DaysInactive = 90 
$time = (Get-Date).Adddays(-($DaysInactive))
$computers = Get-ADComputer -Filter {LastLogonTimeStamp -gt $time} -Properties LastLogonTimeStamp -SearchBase "OU=XX, OU=XX, DC=XX, DC=XX, DC=XX" | Select-Object -ExpandProperty Name


 #get software inventory from active computers
foreach($computer in $computers)
{
    try {Get-WmiObject -Class Win32_Product -ComputerName $computer   | Select-Object pscomputername,name, version, vendor | export-csv c:\psout\software-activeServers.csv -Append
    }
    catch{write-host $computer
    }
 }

 

Reset Windows Permissoins

$
0
0

I need advise in a general 'pseudo-code' discussion on how to accomplish the following.

Objective

-  Recursively set H: drive permissions to all company's user H: drives to a set of predefined permissions

  • Create Owner
  • Domain Admin
  • Local Admin
  • System
  • Full Control of Owner.

I have working code on how to set permissions, inheritance, etc and even reach out to AD properties to set the right user permissions on the folder, but the problem I am having is that this needs to be a universal script that can apply to any folder regardless of what existing permissions are on the folder.   I can't anticipate what permissions to remove across what might be thousands of H; drive folders for users.

I had played with the idea of removing ALL permissions on the folder and then assigning them from scratch.  However after removing all permissions, I can't seem to add anything since I have locked all capability to add a new entry.  

Example;

$acl = Get-Acl c:\utility\test
$acl.Access | %{$acl.RemoveAccessRule($_)}
Set-Acl c:\utility\test $acl

Then when I try to add a default permission...nothing happens to the folder.

 $acl = get-acl C:\utility\test
 $permission  = "corp.clareholdings.com\bclanton","FullControl", "ContainerInherit,ObjectInherit","None","Allow"
 $rule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
 $acl.SetAccessRule($rule)

Can someone offer me logic to consider to accomplish what I want to accomplish?



need a modification to a script

$
0
0

I feel like this would be an easy thing, but some PS stuff is just beyond my immediate comprehension.

I have 3 lines of code that I apply to every user that I add to O365 to allocate a license for them. I put in each line for each user (so, 3 lines per user). I made an excel sheet out of this so at least a little monotony is relieved, but I know this could be better. I would like to know how this could be improved so that it takes input from a file (C:\temp\usernames.txt) and is just a couple of lines of PS code, rather than the mess I currently have.

Without further ado, here's the code:

 

$MyLicenseAssignmentOption = New-MsolLicenseOptions -AccountSkuId "company:ENTERPRISEPACK" -DisabledPlans EXCHANGE_S_ENTERPRISE

Set-MsolUser -UserPrincipalName email@chromalloy.com -UsageLocation US

Set-MsolUserLicense -UserPrincipalName email@chromalloy.com -AddLicenses "company:ENTERPRISEPACK"

Set-MsolUserLicense -UserPrincipalName email@chromalloy.com  -LicenseOptions $MyLicenseAssignmentOption

Your genius is appreciated.

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>