Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

Getting Printer INfo

$
0
0

Hi,

I need to gather inventory for my network. I need the information of the network printers. Since I am new to Powershell and WMI concepts, I have a little doubt about how the Win32_Printer Class gets the information. Does the script scan the printers via the IP address of the machine it is connected to or does it need the IP address of the network printer?

Any help would be really useful for me.

Thanks



the server has returned the following error: invalid enumeration context powershell.

$
0
0

I am getting an error while executing the below Powershell script. I have a huge database of users in active directory. This script gives me desired results but it times out after around 8000 users extracted. This is the error I am getting is the server has returned the following error: invalid enumeration context powershell. Please help.

Get-ADUser -Filter * -SearchBase "OU=abc,DC=xyz,DC=abc" -Properties cn, 

samaccountname, displayName, givenName, middlename, sn, mail, employeeID | Foreach-Object {
    $group = ""
    Get-ADPrincipalGroupMembership $_.SamAccountName | Foreach-Object { 
        if (($_.Name -eq "maple") -or ($_.Name -eq "oak") -or ($_.Name -eq "tree"))
        {
            $group += $_.Name + ","
        } 
    }
    if ($group -eq "")
    {
        $group = "other"
    }
    else 
    {
        $group = $group.Substring(0, $group.Length - 1)
    }   
    New-Object -TypeName PSObject -Property @{
        System_Role = "NONE"
    External_Person_Key = $_.cn
    User_ID = $_.samAccountName
    Passwd = "*****"
    PreferredName = $_.displayName
    FirstName = $_.givenName
    MiddleName = $_.middleName
    LastName = $_.sn
    Email = $_.mail
    Student_ID = $_.employeeID
    Institution_Role = $group
    } | Select-Object System_Role, External_Person_Key, User_ID, Passwd, PreferredName, FirstName , MiddleName, LastName, Email, Student_ID, Institution_Role          
} | Export-Csv -Path "c:\users.csv" 

How to check CPU/Mem/Volume Free space on AIX / Linux using powershell?

$
0
0

I am new to powershell scripting, am able to find scripts to find cpu/mem/swap/diskspace for window.

But could not find much on Linux/Aix using powershell.

How to check CPU/Mem/swap/Volume Free space on AIX / Linux  using powershell?

Thanking you all for all the powerpacked resources on your site.

Receive-Job Output JSON Serializer fails

$
0
0

I am running a Start-Job which returns a nested hashtable. This table/object can contain nested arrays or nested hashtables or even hashtables in arrays. When i try to serialize it using the "New-Object System.Web.Script.Serialization.JavaScriptSerializer", I get the following error: "A circular reference was detected while serializing an object of type  'System.Management.Automation.PSParameterizedProperty'."

Here is my code:

[void] ([System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions"))

$sscript = {
Write-Output -InputObject @(@{name= "maros"},@{name= "Peter"})
}

$j = Start-Job  -ScriptBlock $sscript | Wait-Job | Receive-Job 

$javaScriptSerializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$javaScriptSerializer.MaxJsonLength = [System.Int32]::MaxValue
$javaScriptSerializer.RecursionLimit = 99
$javaScriptSerializer.Serialize($j)

results in :

Exception calling "Serialize" with "1" argument(s): "A circular reference was detected while serializing an object of type 
'System.Management.Automation.PSParameterizedProperty'."
At C:\Users\takacm\AppData\Local\Temp\1a3fa01e-7904-4697-a682-ec12bb2d7625.ps1:13 char:1
+ $javaScriptSerializer.Serialize($j)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : InvalidOperationException
 

However, replacing $j with the same input as the script block output does not throw any error and works as expected !

$javaScriptSerializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$javaScriptSerializer.MaxJsonLength = [System.Int32]::MaxValue
$javaScriptSerializer.RecursionLimit = 99
$javaScriptSerializer.Serialize(@(@{name= "maros"},@{name= "Peter"}))

results in: [{"name":"maros"},{"name":"Peter"}]

Any ideas as to why the Receive-Job Cmdlet causes my output to throw an error when serialized ?

Any help with this would be very much appreciated.

Thanks a lot

Maros


by the way, I am running PS2.0 and can`t upgrade to PS3 or PS4. 

PS1 is not working on remote machine

$
0
0


I am new to poweshell, I have this modified script running file on local PC but cannot use remote call . (Powershell remoting is enabled via GPO )

The script running fine at local host icm  -computername PClocal {c:\folder1\test.ps1}

but not working on remote PCs and no error by using the cmdlet below:

icm -computername pc1 -scriptblock {c;\folder1\test.ps1}


No error at all but just didn't install the software. I think either missing curly bracket or something.

All files are pushed to local C:\folder1 via GPO. I can see them but script  just won't pick them up. It works on my local PC.  

Can I use this one below, which  cause a loop, I am not sure what to put in there.

 

$exe = @('setup.exe','SW_Win7_64Bit.exe')

$msi = @('Service.Installer_Win7')

 

 foreach ($exefile in $exe) 

{start-process -FilePath "c:\folder1\setup\setup.exe" /s 

 start-process -FilePath "c:\folder1\software9000.exe" -ArgumentList "/qn" -Wait

 Start-Process -FilePath "c:\folder\Service.Installer_Win7.msi" -ArgumentList "/qn" -Wait 

}

write-host $file_path

Parameter to generate a log file to a script.

$
0
0

I am using below script. My script is not giving me consistent result.

May i ask, if I can use any statement with a script to get the log file generated so we could find out if my script is extracting exact user count or if it is failing i could get in log file which I could export via email every time it runs.

Any suggestions please? I am a rookie in writing power shell code so please tell me in detail. Thank you

Script I am using.

Import-Module ActiveDirectory

Get-ADUser -Filter { memberOf -RecursiveMatch "CN=status,OU=Test,OU=Users,DC=QA,DC=GU,DC=com" } -SearchBase "OU=Test,OU=Users,DC=QA,DC=GU,DC=com" -Properties cn, samaccountname, givenName, middlename, sn, mail | Foreach-Object {
    $group = ""
    Get-ADPrincipalGroupMembership $_.SamAccountName | Foreach-Object {
        if (($_.Name -eq "staff") -or ($_.Name -eq "student") -or ($_.Name -eq "faculty"))
        {
            $group += $_.Name + ","
        }
    }
    if ($group -eq "")
    {
        $group = "other"
    }
    else
    {
        $group = $group.Substring(0, $group.Length - 1)
    }    
    New-Object -TypeName PSObject -Property @{
        System_Role = "NONE"
    External_Person_Key = $_.cn
    User_ID = $_.samAccountName
    Passwd = "test1"
    FirstName = $_.givenName
    MiddleName = $_.middleName
    LastName = $_.sn
    Email = $_.mail
        Institution_Role = $group
    } | Select-Object System_Role, External_Person_Key, User_ID, Passwd, FirstName , MiddleName, LastName, Email, Role          
} | convertto-csv -Delimiter '|'-notype |% {$_ -replace '"', ""} | out-file c:\BB.dat -Force -Encoding ascii


** Here is need to add statement to get log file***


TechNet

Powershell: More info output?

$
0
0

Morning everyone,

I've been tasked to make a script to remove all group membership from users in a "terminated employees" OU and I need to be able to show what users had what groups remove for auditing purposes.

I've got 2 that "Work" but show different info.

First:

Get-QADUser -SearchRoot 'OU=Canned Employees,DC=Whatever,DC=com' | Remove-QADMemberOf -RemoveAll 

Ends up outputting the groups that have been removed but doesn't show the users that they were removed from.

Second:

Foreach ($user in (Get-QADUser -SearchRoot 'OU=Canned Employees,DC=Whatever,DC=com' )){
(Get-QADUser $user).memberof | Get-QADGroup | where {$_.name -ne "domain users"} | Remove-QADGroupMember -member $user -WhatIf
}

This one outputs the Users that are having there groups removed, but wont list the groups that were removed.(Does show multiple lines for the same user if there are multiple groups removed though)

Anyone know how I can have all the info displayed?

thank you in advance.

Checking for a process using vbscript

$
0
0

Hi all,

Need help with a script. I have a script that is uninstalling trend micros and then installing mcafee. The install leaves up two cmd prompts and as it installs the cmd prompts go away. The second command prompt goes away after about 30 minutes or so. Need a way to track when it completes so I can prompt the user that the script is complete and then write the machine name to a file that it has completed. Here is the code below

ON ERROR RESUME NEXT
Dim file
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FilesystemObject")
set objShell = Wscript.CreateObject("WScript.Shell")

'VPN Check

If objFSO.FolderExists("Some Folder") then
objshell.Popup "YOU ARE CURRENTLY ON VPN/SMITH AND NEPHEW NETWORK." & vbCrLf & "PRESS OK TO CONTINUE.", 60, "IT INFORMATION UPDATE", vbOKOnly

Else
objShell.Popup "UNABLE TO LAUNCH SCRIPT" & vbCrLf & "YOU ARE NOT ON THE VPN/SMITH AND NEPHEW NETWORK." & vbCrLf & VbCrLf & "PLEASE GET ON IT REMOTE ACCESS(FULL) AND RUN THE ATTACHMENT AGAIN.", 60, "IT INFORMATION UPDATE", vbOKOnly
Wscript.Quit
End If

Set file = CreateObject("Scripting.FilesystemObject")
file.DeleteFile("C:\Programdata\Microsoft\Windows\Start Menu\Programs\Startup\Message.vbs")

'GPUpdate
WshShell.Run "%comspec% /c gpupdate /force"
WScript.Sleep(90000)


'Uninstall Trend Micro
 If objFSO.FileExists("C:\Program Files (x86)\Microsoft Office\Office14\Winword.exe") Then
  WshShell.Run """C:\Program Files (x86)\Trend Micro\OfficeScan Client\ntrmv.exe"" -980223" ,0,True
 ElseIf objFSO.FileExists("C:\Program Files\Microsoft Office\Office14\Winword.exe") Then
  WshShell.Run """C:\Program Files\Trend Micro\OfficeScan Client\ntrmv.exe"" -980223" ,0,True
 Else   WScript.Echo "having trouble"
 End If

'Install McAfee
 If objFSO.FileExists("C:\Program Files (x86)\Microsoft Office\Office14\Winword.exe") Then
  WshShell.Run "%comspec% /c E: & cd ""\McAfee\Agent\v4.5.0.1852\"" & cscript Appsetup(x64).vbs"
  WshShell.Run "%comspec% /c E: & cd ""\McAfee\VSE&ASE\v8.8 with Patch1\"" & cscript Appsetup(x64).vbs"
 ElseIf objFSO.FileExists("C:\Program Files\Microsoft Office\Office14\Winword.exe") Then
  WshShell.Run "%comspec% /c E: & cd ""\McAfee\Agent\v4.5.0.1852\"" & cscript Appsetup(x86).vbs"
  WshShell.Run "%comspec% /c E: & cd ""\McAfee\VSE&ASE\v8.8 with Patch1\"" & cscript Appsetup(x86).vbs"
 Else   WScript.Echo "Trouble Installing McAfee! Please call SNBio IT at and select Option 2 for support."
        WScript.Quit
 End If
 
WScript.Quit


Christopher




AD Cleanup - Script to disable and move old AD accounts

$
0
0

I have been tasked with cleaning up users in our domain. I have some Powershell experience, but am kind of stuck. I have the first part of a script that returns the users in a particular OU that have lastlogondate and passwordlastset attributes of 360 days or greater. I have created a variable called $user that contains all the information returned in the first part of the script. I now need to, using a foreach loop I assume, disable these accounts and move them to a specific OU in our AD. I have included the script I have so far below. Any advice on this would be greatly appreciated.

$Days=(get-date).adddays(-360)

$user

=Get-ADUser-SearchBase"OU=Customers,DC=OPI,DC=LOCAL"-filter{(lastlogondate-notlike"*"-ORlastlogondate-le$Days)-AND(passwordlastset-le$Days)-AND(enabled-eq$True)}-Propertieslastlogondate,passwordlastset|Select-Objectname,lastlogondate,passwordlastset

$user

|ft-autosize

foreach

($uin$user){

Thank you!

Robocopy: Copy Files without folder structure

$
0
0

I want to copy all te files with *.jpg extention from a directory (and subdirectories)

to a new folder. but i don't want the treestructure in the destination folder. 

 

Is this possible?

 

many Thanks

Active Directory scripting help

$
0
0

I am trying to clean up our group policies so I am in need of help creating a script that will list all group policies in our domain, list all the settings that are set in each GPO, and the security filtering for each gpo and also list any settings that are duplicated in another policy and exports it into a readable (by me) file. I am familiar with batch scripts, VB Scripts, and PowerShell so something in these forms is good for me but I am moderately familiar with VB Scripts and beginner with PowerShell scripts.

Thank you

Error when attempting to move AD-User

$
0
0

Receiving error :" Move-ADObject : The operation could not be performed because the object's parent is either uninstantiated or deleted"

My Script:

import-module activedirectory
import-csv c:\mylist.csv |
    foreach-object{
        $user=Get-AdUser $_.userid
        $dn=$user.distinguishedname
        $parent=([adsi]"LDAP://$dn").Parent.Replace('LDAP://','')
        $newdn="OU=disabled accounts,$parent"
        $newdn -replace "OU=Temporary Accounts,",  ""
        $user | Disable-ADAccount
        $user | Move-ADObject -targetpath $newdn -targetserver mgw-2k3-dc1.xyz.com
    }

So I tried  specifying a -targetserver, I receive error:

Move-ADObject : Can't move objects with memberships across domain boundaries as on
ce moved, this would violate the membership conditions of the account group. Remov
e the object from any account group memberships and retry

I'm assuming I'll have to query for the DC they reside on and make that the target for each object?


Test Exchange Services on all servers one cmd

$
0
0

Guys is there any way i can run the below in one cmd as i tried but getting a below error  i am try to check the exchange services from one cmd let instead of simple script

----------------------------------

$ExchServer=Get-ExchangeServer
foreach ($Server in $ExchServer)
{
echo $Server.name (Test-ServiceHealth $Server)
}

------------------------------------

Error***********

[PS] C:\Windows\system32>$ExchServer=Get-ExchangeServer | foreach ($Server in $ExchServer) {echo $Server.name (Test-ServiceHealth $Server)}
Unexpected token 'in' in expression or statement.
At line:1 char:53
+ $ExchServer=Get-ExchangeServer | foreach ($Server in <<<<  $ExchServer) {echo $Server.name (Test-ServiceHealth $Serve
r)}
    + CategoryInfo          : ParserError: (in:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

Copy File from One Location to Another Location through xcopy or any

$
0
0

Hi,

I Need to copy one file from one location to another location. That file need to save in C:\Windows\System32 folder

I need to create one .bat file and i want apply that bat as a startup script through GPO.

I tried through XCopy if i test in machine that is working. If i tried in other machine that is not working. becoz of some Credential issue

I tried in the script by netuse command after that my script itself not working.

SET username=XYZ\Administrator

SET password=abcd

@ECHO OFF

cmd "cd C:\"

net use "\\10.50.5.68\c$\Windows\System32" %password% /user:domain\%username%

:copy

Xcopy /S /I /E D:\DLL \\10.50.5.68\c$\Windows\System32 



Regards, Hari Prasad.D

PowerShell converting System.Byte[]

$
0
0

Hi,

We have something writing garbled data to some of our extensionData attributes, on some of our Distribution Lists. I'll use repadmin /showobjmeta to track down the offending user account but in the meantime I'm trying to output this particular attribute to csv in order to find out which ones have been borked.

Here's my current command:

get-adgroup -filter * -properties extensionData,whenChanged | where-object{$_.extensionData -ne ""} | select distinguishedname, @{L='extensionData'; E={$_.extensionData -join ";"}}, whenChanged | export-csv out.csv -NoTypeInformation

This then returns the DN, the date the object was changed and for extensionData:

System.Byte[]

or for some:

System.Byte[];System.Byte[];System.Byte[];System.Byte[];System.Byte[];System.Byte[]

Etc.

I'm struggling to convert what I believe to be a hexadecimal value into a readable string and hoped someone could help.

If I don't include the line:

@{L='extensionData'; E={$_.extensionData -join ";"}}

Then for the extensiondata attrib the csv shows:

"Microsoft.ActiveDirectory.Management.ADPropertyValueCollection"

Thanks!


How can I force close an application ( same as end task ) and restart again using VBScript ?

$
0
0

Hi,

I have an application running on a remote server, which should be force closed ( End Task )and reopened ( start ) again. Daily we use to log into the server to carryout this task.

Need some help using Powershell to automate this task.

Thanks

Ireshad

PowerShell 4.0 Update-Help does not work in Windows 7 SP1

$
0
0
PowerShell 4.0 Update-Help does not work in Windows 7 SP1. Please advice.

How to change maintenance powershell script via GPO?

$
0
0

Per suggestion reposted from here: http://social.technet.microsoft.com/Forums/windowsserver/en-US/6eece9d6-a524-48aa-8e64-7554f0ec9b31/how-to-change-maintenance-powershell-script-via-gpo?forum=winserverGP

Posted at http://answers.microsoft.com/en-us/windows/forum/windows_7-desktop/desktop-shortcuts-to-items-on-network-drives/94eddb27-342b-40fc-9ad4-677ff4ee8ebe?page=9&tm=1403700614489 originally.

There is a very annoying "feature" in Windows 7 called BrokenShortcuts.ps1 which is being called out weekly via maintenance task and if it finds more than 4 "broken" network shortcuts it removes them all. So it means if a user at this moment is disconnected from the network he will lose all links to shares, network applications sitting on his desktop. Funny that there was no such script on Vista and i don't see this on Win8. On the post i have attached one user suggested to edit this script and change 4 to 500 or whatever high number. That's fine for one time fix. But i need to do this for 200+ users. This file cannot be simply replaced by a script, so i'm wondering is there any way to do it via GPO?

I have already tried various startup scripts, but i'm not sure which user to put into commands.

I need to run this on startup:

takeown /F C:\Windows\diagnostics\scheduled\Maintenance\TS_BrokenShortcuts.ps1
icacls c:\windows\diagnostics\scheduled\maintenance\TS_BrokenShortcuts.ps1 /grant "some user":F
copy \\share\folder$\TS_BrokenShortcuts.ps1 C:\Windows\diagnostics\scheduled\Maintenance\ /Y

Powershell scripting 2.0

$
0
0

I'm unable to get the switch statement in my guess the number game to work.  Can you tell me what I'm missing?

$playGame = "Yes"    #Controls when to quit the game
$randomNo = New-Object System.Random  #This variable stores a random object
$status = "Play"    #Controls the current round of play
$guess = 0        #Stores the player's guess
$reply = ""        #Stores the players's response when asked to play again
$noOfGuesses = 0    #Keeps track of the number of games user has played
$choice = 0
$number = 0

#Loop until the player decides to quit the game
while ($playGame -ne "No") {

Clear-Host

#Loop until the player guesses the secret number
while ($status -ne "Stop") {
    
#Prompt the player to guess a number
while ($guess -eq "") {
clear-Host
write-Host
#Collect the player's guess
$guess = Read-Host " Select a level of play."


if ($guess -eq "Q") {
Clear-Host
Write-Host "`n`n"
Write-Host " Game over. Thanks for playing."
Write-Host "`n`n`n`n`n`n`n`n"
Write-Host " Press Enter to continue."
        
Read-Host
$status = "stop"
$playgame = "No"
continue
}
$choice = $guess

switch ($choice)
 {
    1 {$number = $randomNo.Next(1,11)}
    2 {$number = $randomNo.Next(1,51)}
    3 {$number = $randomNo.Next(1,101)}
    default {write-host "Invalid input. Please try again."
}
    
if ($guess -lt $number) { #The player's guess was too low
Clear-Host
Write-Host "`n Sorry. Your guess was too low. Please pick a higher number."
write-host "`n Press Enter to guess again."
$guess = "" #reset the player's guess
Read-Host
}

elseif ($guess -gt $number) { #The player's guess was too high
Clear-Host
Write-Host "`n Sorry. Your guess was too high. Try and pick a" `
        "mid-range number."
write-host "`n Press Enter to guess again."
$guess = ""  #Reset the player's guess
Read-Host
}


else { #The player has guessed the game's secret number
Clear-Host
Write-Host "`n Congratulations. You guessed my number! Press Enter" `
    "to continue."
$status = "stop"    #Reset the player's guess
Read-Host
}


}

#Prompt the player to play another round
while ($reply -eq "") {

Clear-Host
Write-Host
#Collect the player's answer
$reply = Read-Host " Would you like to play again? (Y/N) "
#Validate player input, allowing only Y and N as acceptable responses            

if (($reply -ne "Y") -and ($reply -ne "N")) {
$reply = "" #Reset the variable to its default value
}
}

$noOfgames++

#The player has elected to play again
if ($reply -eq "Y") {
#Reset variable to their default values        
$number = 0
$noOfGuesses = 0
$status = "Play"
$guess = 0
}

elseif ($reply -eq "N") {
#The player has decided to quit playing
$playGame = "No"     #Modify variable indicating time to terminate gameplay
clear-host
Write-Host "`n Game Statistics"
Write-Host " _________________________________________"
Write-Host "`n You played $noOfGames game(s).`n"
write-host "__________________________________________"
write-host "`n The number of low guesses were $lowguess."
write-host "`n The number of High guesses were $highguess."
write-host "`n`n`n`n`n`n`n`n`n`n` Press Enter to continue."
read-host
}
}
}

Clear-host

vbscript delete folders except difine in exception

$
0
0

Dear,

need support for below script for deleting all folders except in exception.

Its deleting all


Dim Exception
Exception = Array("Test2")


Function Deletfdrs()
    Dim fso, f, f1, fc, i
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.GetFolder("C:\Temp1\")
    Set fc = f.SubFolders
    
         ForEach f1in fc
                        
            For i = 0toUBound(Exception)
            
           If f1.name = Exception(i) Then f1.Delete = False
           
        Next
        
                       
   f1.Delete
    
        'If delete = True Then msgbox(f1.name)'f1.delete
    Next
EndFunction


Support@Mytechnet.me

Viewing all 15028 articles
Browse latest View live


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