I want to write a powershell script to clear specific printer queues from csv

This is what I have so far, but doesn't seem to be working. Any help would be appreciated.
$InCSVPath = "c:\printeraddscript\printerremove.csv"
$csv = Import-Csv $InCSVPath
foreach($item in $csv){     
       $server = $item.Server + ".Domain name here"  
       $printer = $item.Printer  
       $a = Get-WmiObject Win32_PrintJob -ComputerName $server -Filter "Name='$printer'" }
foreach ($job in $a)
   "Canceling job $($job.JobId)"   

Import-Csv c:\printeraddscript\printerremove.csv |
ForEach-Object{
Get-WmiObject Win32_Printer -ComputerName $_.server -Filter "Name='$($_.printer)'" } |
ForEach-Object{
$_.CancelAllJobs()
¯\_(ツ)_/¯

Similar Messages

  • To write a perl script for running a java program from cgi of web server

    I have to write a perl script to call a java program(.exe).I want to run this file through the cgi of the web server.
    java myprogram
    can anyone help me to write a perl script??

    It depends on what the java program does. For example, does it parse HTTP headers from standard input, or what?
    Are you sure it wouldn't be easier to turn the class into a servlet? etc.
    Take a look at IPC::Open2 and IPC::Open3 though. You may need them. (That's just a guess.)

  • Powershell script to search specific event ID's from Archive Event files

    Hi,
    I have to search some Windows Event ID's from Archive event (evtx) files. for that i am trying powershell code mentioned on below link but its not working. Kindly suggest how to search specific event id from archive logs.
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/83cbf185-bd96-4efc-b36b-59439024960a/parse-message-property-from-archived-eventlog
    Regards,
    Dhiraj

    Hi,
    Thanks for your response. I am using below code & getting below message. I changed the event ID & got some results. Can we remove those lines form results where record not found. like how can we get only those records which match given
    event ID. also it's not showing all field values. Is there any formating issue.
    $SearchID='4740' 
    get-childitem "C:\Windows\System32\Winevt\Logs\Archive-Security*.evtx" | select FullName | forEach{
     %{get-winevent  -filterHashTable @{path=$_.Fullname;ID=$SearchID} |                
        ? {$_.Properties[5].Value -match $UserName} |   
        Select-Object -Property TimeCreated, `
                                @{Name='SecurityId';Expression={$_.Properties[4].Value}}, `
                                @{Name='AccountName';Expression={$_.Properties[5].Value}}, `
                                @{Name='AccountDomain';Expression={$_.Properties[6].Value}}, `
                                @{Name='LogonId';Expression={$_.Properties[7].Value}}, `
                                @{Name='LogonType';Expression={$_.Properties[8].Value}}, `
                                @{Name='Workstation';Expression={$_.Properties[11].Value}}, `
                                @{Name='LogonGuid';Expression={$_.Properties[12].Value}} |
        Format-Table
    Get-WinEvent : No events were found that match the specified selection criteria.
    At C:\Users\sidadmin1\Documents\EventIDCheck.ps1:3 char:16
    +  %{get-winevent <<<<   -filterHashTable @{path=$_.Fullname;ID=$SearchID} |
        + CategoryInfo          : ObjectNotFound: (:) [Get-WinEvent], Exception
        + FullyQualifiedErrorId : NoMatchingEventsFound,Microsoft.PowerShell.Commands.GetWinEventCommand
    TimeCreated    SecurityId     AccountName     AccountDomain LogonId        LogonType      Workstation    LogonGuid
    3/11/2014 4... DC04$          MyDomain                 999
    Get-WinEvent : No events were found that match the specified selection criteria.
    At C:\Users\sidadmin1\Documents\EventIDCheck.ps1:3 char:16
    +  %{get-winevent <<<<   -filterHashTable @{path=$_.Fullname;ID=$SearchID} |
        + CategoryInfo          : ObjectNotFound: (:) [Get-WinEvent], Exception
        + FullyQualifiedErrorId : NoMatchingEventsFound,Microsoft.PowerShell.Commands.GetWinEventCommand
    Dhiraj

  • PowerShell - Rename Contents of File Using names From CSV

    I have the following script where the user is asked for the file server IP address, the IP is entered and the gpreport.xml file modified as needed.
    $file_server = Read-Host "Enter the file server IP address"
    $rootFolder = 'C:\TEMP\GPO\source\5'
    Get-ChildItem -LiteralPath $rootFolder -Directory |
    Where-Object { $_.Name -as [System.Guid] } |
    ForEach-Object {
    $directory = $_.FullName
    (Get-Content "$directory\gpreport.xml") |
    ForEach-Object { $_ -replace "99.999.999.999", $file_server } |
    Set-Content "$directory\gpreport.xml"
    # ... etc
    This works well, but I would like to automate it using a reference CVS file. I have 3 columns in my file - FQDN, Server Name and Server IP. I need PowerShell to identify current logged on users domain name ($env:userdnsdomain) and match the
    result to the CSV file below. Once matched, take the server IP column and insert it into gpreport.xml . This way the user insnt being asked for the Ip address of the $file_server and it's being done automatically.
    Thank you.

    Hi,
    Here's an example you can use:
    Import-Csv .\input.csv | ForEach {
    If ($_.FQDN -eq $env:USERDNSDOMAIN) { $file_Server = $_.'Server IP' }
    $file_Server
    Don't retire TechNet! -
    (Don't give up yet - 12,700+ strong and growing)

  • Does anyone have a PowerShell script which change the paper source on a Canon Image Runner Advance?

    I came across this Powershell script on the web, which does a good job of printing out PDFs:
    Start-Process -FilePath "C:\Users\Test\Documents\Listing.pdf” –Verb Print -PassThru | %{sleep 10;$_} | kill
    Start-Process -FilePath “C:\Users\Test\Documents\Scan0001.pdf” –Verb Print -PassThru | %{sleep 10;$_} | kill
    Start-Process -FilePath “C:\Users\Test\Documents\Scan0004.pdf” –Verb Print -PassThru | %{sleep 10;$_} | kill
    See: http://gregcaporale.wordpress.com/2012/01/18/powershell-to-print-files-automatically/ 
    What I want to know is, does someone know how to write a Powershell script so that before printing out each PDF, a tab will be pulled from a separate paper source tray.  I need the Powershell script to
    1. Set the paper source to tray 4 where the tabs are.
    2. Print a one page PDF which just reads "Tab 1" or whatever, on the tab itself
    3. Set the paper source to ray 1 where letter sized paper is.
    4. Print a PDF of the document to go behind tab 1.
    . . . and then repeat.
      I am working with a Canon Image Runner Advance copier/printer into which tabs can be loaded. It includes an insert sheets setting in the properties, which allows a user to specify the pages where a tab or slip sheet should go.  But I don't want to deal with creating a very large PDF, and then identifying all of the pages where an insert should occur.

    Here is the powershell code for adding ips to relayiplist..hope this helps.
    this code will take the ips of the host machine and add it to the relayiplist...works for me...
    $Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName localhost | ? {$_.IPEnabled}
    $ipblock= @(24,0,0,128,
    32,0,0,128,
    60,0,0,128,
    68,0,0,128,
    1,0,0,0,
    76,0,0,0,
    0,0,0,0,
    0,0,0,0,
    1,0,0,0,
    0,0,0,0,
    2,0,0,0,
    1,0,0,0,4,0,0,0,0,0,0,0,76,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255)
    $ipList = @()
    $octet = @()
    foreach ($Network in $Networks)
         $ipList = $Network.IpAddress[0]
            $octet += $ipList.Split(".")
            $ipblock[36] +=1
            $ipblock[44] +=1;
    $smtpserversetting = get-wmiobject -namespace root\MicrosoftIISv2 -computername localhost -Query "Select * from IIsSmtpServerSetting"
    $ipblock += $octet
    $smtpserversetting.RelayIpList = $ipblock
    $smtpserversetting.put()
    kautilya

  • PowerShell Script to Clean User Profiles File Location

    Hello,
    I have been searching around to accomplish what I am trying to do. It is pretty basic so I am hoping someone can point me in the right direction. I want to write a powershell script to clean out two locations in all the user profiles on a Citrix server.
    Here are the steps I'd like to accomplish.
    1. Find all user profiles on the Citrix server
    2. Delete all the files from these two locations; "\Local Settings\Application Data\Mozilla\*.*" and "\Local Settings\Application Data\Microsoft\OneNote\*.*"
    This will run on a weekly basis via a scheduled task. A nice to have would be to add any profile over 60 days old.
    I have a pretty good start, but I am still learning PowerShell, so any help would be appreciated.
    Thanks in advance!
    Thanks, Jeremy

    Hello mbwc,
    how about showing us what you got so far and detail where you have trouble?
    That way, we can help you understand your problems and find the solution yourself (= good for learning), instead of having one of us simply provide the solution (= bad for learning).
    Cheers,
    Fred
    There's no place like 127.0.0.1

  • How to combine 3 PowerShell scripts to write results to CSV file?

    Hello,
    I have 3 domains, and I like to combine the results from the Get-ADUser and write the results into one CSV file.  Can this be done?  How to do this?  Below are the 3 Get-ADUser
    scripts:
    Get-ADUser -Filter {enabled -eq "true" -and title -like "*"} -SearchBase "DC=domain1, DC=com" -Properties hiredate, department, surname, displayname  export-csv "d:\scripts\pbtfusers.csv"
    Get-ADUser -Filter {enabled -eq "true" -and title -like "*"} -SearchBase "DC=domain2, DC=com" -Properties hiredate, department, surname, displayname  export-csv
    "d:\scripts\pbtfusers.csv"
    Get-ADUser -Filter {enabled -eq "true" -and title -like "*"} -SearchBase "DC=domain3, DC=com" -Properties hiredate, department, surname, displayname  export-csv
    "d:\scripts\pbtfusers.csv"
    Paul

    Sure:
    Get-ADUser tester1 | Export-Csv .\userOutput.csv
    Get-ADUser tester2 | Export-Csv .\userOutput.csv -Append
    Get-ADUser tester3 | Export-Csv .\userOutput.csv -Append
    Sample output:
    PS C:\Scripts\PowerShell Scripts\Misc Testing\9-3-2014> Import-Csv .\userOutput.csv | Select Name
    Name
    tester1
    tester2
    tester3
    This is an extremely simplified example. It returns three user objects and writes them all to the output file one at a time.
    Don't retire TechNet! -
    (Don't give up yet - 13,085+ strong and growing)

  • How to export Powershell script information to Sharepoint?

    I'm trying to export information gather from a Powershell script to a Sharepoint list. I've got a couple of powershell scripts that gather general server information from a server ex: server uptime, disk space, service tag, etc. and it will export the information
    to a csv file. What I would like to do is out-put the same information gathered by the powershell scripts to a Sharepoint list directly if at all possible.
    Ex:
    # all this does is reads from a list and runs a script call "boottime.ps1"
    get-content "\\%Data-Path-Of-List%\computers.txt" | %Data-Path-Of-Script%\boottime.ps1 |  Export-csv %Data-Path-For-CSV\Computers.csv
    # then just exports the information from the boottime.ps1 script to a csv file
    #I also have a script that will upload the information to a sharepoint list.
    # I found that I have to run this in version 2 of powershell, so I just open a DOS prompt in Admin Priv's and type the following
    powershell.exe -version 2.0
    # Next I make sure the Sharepoint snap-in is loaded
    if ( (Get-PSSnapin -Name Microsoft.sharepoint.powershell - erroraction silentlycontinue) -eq $null)
    Add-PsSnapin Microsoft.Sharepoint.Powershell
    $spweb = get-SPweb $spserver
    $spdata =$spweb.getlist("%URL_Of_My_List%")
    # this is the same location from the orginal Powershell script previously stated.
    $ComputerInfoFile = "%Data-Path-For-CSV%\Computers.csv"
    foreach ($rows in $tblData) {
    # here is where I add the information from my csv file
    # 2 things needs to be present
    # 1st the colums have to be present in the sharepoint site before I can upload the information
    # 2nd the columns have to the headers in my csv file
    $spItem = $spData.AddItem()
    $SpItem["ServerName"] = $row."ServerName".toString()
    $SpItem["Uptime"] = $row."Uptime".toString()
    $SpItem.Update()
    # this just disconnects from Sharepoint
    $spWeb.Dispose()
    Please dismiss all the comments it just helps me understand what the code is doing, also if this is not the correct place to post this question I appologize in adavance and ask that if this is the incorrect place to post this question please provide me a
    link to a where I can post such questions.

    Sorry for the delay in posting this, but I ended up getting working. I'll post it in the hopes that my head scratching will save someone else some head scratching:
    I ended up writting 3 PS scripts and one batch job.
    1st Batch file
    powershell.exe -version 2.0 -command
    \\%Script-Location\Get-Server-Infor-4-SP.ps1
    powershell.exe -version 2.0 -command \\%Script-Location\Delete-list-Items.ps1"
    powershell -veriosn 2.0 -command
    \\%Script-Location\Populate-SP.ps1
    1st PS script that gets the info:
    get-content
    \\%Location-Of-My-File-With-List-Of-Servers%\%name-of-file%.txt |
    \\%Location-Of-My-Script-To-get-the-Information-I-want | Export-csv
    \\%location-of-my-output\%filename%.csv
    Ex: get-content C:\scripts\computers.txt | C:\scripts\boottime.ps1 | export-csv C:\scripts\computer.csv
    2nd PS script Delete-List-Items.ps1
    # http:
    #Script 1 Boottime.ps1:
    # This script permits to get UpTime from localHost or a set of remote Computer
    # usage
    # localHost
    # .\BootTime.ps1
    # set of remote computers
    # get-content .\MyserverList.txt | .\boottime.ps1
    # Optionally pipe output to Export-Csv, ConverTo-Html
    Process {
    $ServerName = $_
    if ($serverName -eq $Null) {
    $serverName= $env:COMPUTERNAME
    $timeVal = (Get-WmiObject -ComputerName $ServerName -Query "SELECT LastBootUpTime FROM Win32_OperatingSystem").LastBootUpTime
    #$timeVal
    $DbPoint = [char]58
    $Years = $timeVal.substring(0,4)
    $Months = $timeVal.substring(4,2)
    $Days = $timeVal.substring(6,2)
    $Hours = $timeVal.substring(8,2)
    $Mins = $timeVal.substring(10,2)
    $Secondes = $timeVal.substring(12,2)
    $dayDiff = New-TimeSpan $(Get-Date –month $Months -day $Days -year $Years -hour $Hours -minute $Mins -Second $Secondes) $(Get-Date)
    $Info = "" | select ServerName, Uptime
    $Info.servername = $servername
    $d =$dayDiff.days
    $h =$dayDiff.hours
    $m =$dayDiff.Minutes
    $s = $daydiff.Seconds
    $info.Uptime = "$d Days $h Hours $m Min $s Sec"
    $Info
    #Script 2: Delete-List-Items.ps1
    # http://markimarta.com/sharepoint/delete-all-items-in-sharepoint-list-using-powershell/
    # there seems to be a problem with running this script in version 3 or later, the workaround is to run it in version 2
    # below is the cmd for doing so, just open up a DOS prompt with Admin Privileges Start-->Run-->cmd
    # type then copy and paste the following line the DOS window then you can run this script
    #powershell.exe -version 2.0
    # make sure that the Microsoft.SharePoint.PowerShell Snap-in is installed as well
    if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
    Add-PsSnapin Microsoft.SharePoint.PowerShell
    # "Enter the site URL instead http://serverurl"
    $SITEURL = "%http://serverurl%"
    $site = new-object Microsoft.SharePoint.SPSite ( $SITEURL )
    $web = $site.OpenWeb()
    "Web is : " + $web.Title
    # Enter name of the List below in the [“%List-Name%”]
    $oList = $web.Lists["%List-Name%"];
    # This echo out the name of the list its going to be deleting the records from
    "List is :" + $oList.Title + " with item count " + $oList.ItemCount
    # It’s just counting the rows/records
    $collListItems = $oList.Items;
    $count = $collListItems.Count - 1
    # Here is where it is actually deleting the records and then out put the number or the record it deleted
    for($intIndex = $count; $intIndex -gt -1; $intIndex--)
    "Deleting record: " + $intIndex
    $collListItems.Delete($intIndex);
    #Script 3: Populate-SP_Test.ps1
    # http://blogs.technet.com/b/stuffstevesays/archive/2013/07/10/3577320.aspx
    # there seems to be a problem with running this script in version 3 or later, the workaround is to run it in veriosn 2
    # below is the cmd for doing so, just open up a DOS prompt with Admin Privileges Start-->Run-->cmd
    # type then copy and paste the following line the the DOS window then you can run this script
    #powershell.exe -version 2.0
    # make sure that the Microsoft.SharePoint.PowerShell Snap-in is installed
    if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
    Add-PsSnapin Microsoft.SharePoint.PowerShell
    # Here are some more varables that can be added I was not able to get this to work
    #$SPComputerInfo="/Lists/PowershellTest/"
    # Here is where we connect and Open SharePoint List via Powershell
    $SPServer= "%http://serverurl%
    $spWeb = Get-SPWeb $SPServer
    $spData = $spWeb.GetList("%List-Name%")
    # This is the variable for the path that has the file I want to input to SharePoint List
    $InvFile="\\%location-ofList%\computers.csv"
    # This is just some error checking to make sure the file exist
    $FileExists = (Test-Path $InvFile -PathType Leaf)
    if ($FileExists) {
    "Loading $InvFile for processing..."
    $tblData = import-csv $InvFile
    } else {
    "$InvFile not found - stopping import!"
    exit
    # Loop through Applications add each one to SharePoint
    "Uploading data to SharePoint...."
    foreach ($row in $tblData) {
    #Here is where I add the information from my CSV file
    #2 things have to be present
    # 1. the columns have to be in the sharepoint site before I can import the information
    # 2. columns have to the headers in my csv file
    #"Adding entry for "+$row."Computer Information".ToString()
    $spItem = $spData.AddItem()
    $spItem["ServerName"] = $row."ServerName".ToString()
    $spItem["Uptime"] = $row."Uptime".ToString()
    #$spItem["DNSHostName"] = $row."DNSHostName".ToString()
    #$spItem["DistinguishedName"] = $row."DistinguishedName".ToString()
    $spItem.Update()
    # This is just disconnecting from SharePoint
    $spWeb.Dispose()
    Enjoy, and if anyone has a better way of doing this I'm interested in knowing, thanks again
    Thanks in Adavance

  • SCCM 2012 PowerShell script gets progressively slower with each machine added to a collection

    Firstly, I hope this question firs in this forum.
    I have a PowerShell script that I created the imports a CSV file and adds the machine names to a collection as a direct membership. There are 5000 machines total in the list. When the script first starts, the average per machine is just a few tenths of a
    second. Once it reaches about 10% the average is up to almost 4 seconds and that time is getting larger with each machine. I tried using the CMDLets for SCCM but they were even slower than the WMI seemed to be.
    What is the reason for this increase?
    Is there anything I can do to not have this happen?
    My script:
    $ErrorActionPreference= 'continue'
    $FilesInFolder = Get-ChildItem $PSScriptRoot
    $CSVFiles = $FilesInFolder | where {$_.extension -eq ".csv"}
    $SiteCode = "US1"
    Function AddToCollection-WithWMI
    ForEach ($File in $CSVFiles)
    $CollectionStart = Get-Date
    $CollectionName = $File.Name.TrimEnd(".csv")
    $PClist = Import-CSV $File.FullName
    Write-Host "Populating Collection: " $CollectionName
    $i = 1
    $PCRollingTime = New-Object System.TimeSpan
    ForEach($PC in $PClist)
    $PCStart = Get-Date
    $ResourceName = $PC.SerialNumber
    Write-Host $i "of" $PClist.Count
    $ResourceQuery = Get-WmiObject -Namespace "Root\SMS\Site_US1" -Class SMS_R_SYSTEM -Filter "Name = '$ResourceName'"
    $CollectionQuery = Get-WmiObject -Namespace "Root\SMS\Site_US1" -Class SMS_Collection -Filter "Name = '$CollectionName' and CollectionType='2'"
    $CollectionQuery.Get()
    IF($ResourceQuery -ne $null)
    #Create new direct membership rule
    $NewRule = ([WMIClass]"\\Localhost\root\SMS\Site_US1:SMS_CollectionRuleDirect").CreateInstance()
    $NewRule.ResourceClassName = "SMS_R_System"
    $NewRule.ResourceID = $ResourceQuery.ResourceID
    $NewRule.Rulename = $ResourceQuery.Name
    #Commit changes
    $CollectionQuery.CollectionRules += $NewRule.psobject.baseobject
    $CollectionQuery.Put() | Out-Null
    $NewRule = $null
    ELSE
    Write-Host "No Device ID found for: " $PC.SerialNumber
    $CollectionQuery = $null
    $ResourceQuery = $null
    $PCFinish = Get-Date
    $TimeSpan = New-TimeSpan -Start $PCStart -End $PCFinish
    $PCRollingTime = $TimeSpan + $PCRollingTime
    If(($i % 25) -eq 0)
    $CurrentAvgPerPC = $PCRollingTime.TotalSeconds / $i
    Write-Host "The current average is" $CurrentAvgPerPC "seconds."
    $SecondsToETA = ($CurrentAvgPerPC * ($PClist.Count - $i))
    $ETA = Get-Date
    $ETA = $ETA.AddSeconds($SecondsToETA)
    Write-Host "The Estimated time of complete is" $ETA
    If(($i % 250) -eq 0)
    $PCRollingTime
    $i++
    $CollectionQuery = Get-WmiObject -Namespace "Root\SMS\Site_US1" -Class SMS_Collection -Filter "Name = '$CollectionName' and CollectionType='2'"
    $CollectionQuery.Get()
    #Initiate the collection evaluator
    $CollectionQuery.RequestRefresh()
    $CollectionFinish = Get-Date
    AddToCollection-WithWMI

    I haven't checked the complete code, but it doesn't look very efficient. For example I would take the collection query out the loop for all the pcs, simply because it's always the same and would save you about 4999 queries.
    My Blog: http://www.petervanderwoude.nl/
    Follow me on twitter: pvanderwoude
    ^^ This 
    Additionally, you could likely replace most of the WMI calls you do with the built in SCCM PowerShell cmdlets.  The two lines below will check to see if a Device Object for a specific PC exists and if it does, adds it to your collection
    $PCID = Get-CMDevice -Name $PC.SerialNumber
    if ($PCID -ne $null) {
    Add-CMDeviceCollectionDirectMembershipRule -CollectionName $CollectionName -ResourceId $PCID
    If you want to check to see if the collection exists before trying to add devices to it, you can use the Get-CMDeviceCollection cmdlet.
    Get-CMDeviceCollection -Name $CollectionName
    Moo.

  • Powershell script to get Site Collection. Site Owner, Title

    Hi,
    I am new to SharePoint, currently I have given one task to create the powershell script which contains the below fields from our two farms. Could you please help me out with the same.
    The script to list out below items:
    Site Collections:
    Site Collection Name:
    Site Collection Owners:
    Last Activity and the size of site collections.
    Many Thanks & Best Regards,
    Naren

    To get all Site Collections:
    If all you want is a list of all site collections in the farm, all you have to do is open a PowerShell window, load the SharePoint Snapin, if you haven't (Add-PSSnapin
    Microsoft.SharePoint.PowerShell), and type Get-SPSite.
    If you want to return the list of site collections for a specific web application, the easiest way is to just pipe it as Get-SPWebApplication
    http://intranet | Get-SPSite
    To get Site Collection Owners:
    Add-PSSnapin "Microsoft.SharePoint.Powershell" -ErrorAction SilentlyContinue
    Get-SPWebApplication "http://mySharePointSite.com"|
    Get-SPSite| foreach-object{ Write-host$_.Url - $_.Owner.Email}
    To get Size of all Site Collections:
    Get-SPSite | select url, @{label"Size in MB";Expression={$_.usage.storage/1MB}} | Sort-Object
    -Descending -Property "Size in MB" | ConvertTo-Html -title "Site Collections sort by size" | Set-Content sc.html
    Regrading the retrieving the last activity I am not sure to what exactly you are looking for but I assume you are concern about getting users last logon time and date using PowerShell.
    For this refer here: Get Users Last Logon Time and Date using PowerShell
    Please remember to upvote if it helps you or
    click 'Mark as Answer' if the reply answers your query.

  • [PowerShell] Script to restart a service and its dependents (and their dependents)

    I am trying to write a PowerShell script that will restart the SNMP Service on a server.  The server in question is an HP server that has the various HP Insight agents installed, and some of these depend on the SNMP Service.  One of these services
    also depends on one of the other HP Insight services (that in turn depends on SNMP Service).
    I can easily write a script that stops and starts the specific services in order, but I don't want to do that.  I like to create scripts that are as flexible as possible.  In this case, I'd like to write a script that takes a service name as input
    and can restart that service, including any dependents (and dependents of those dependents, and dependents of those dependents).  They way to do this seems to be recursion, but I simply cannot get it to work correctly.  Here is what I have so far
    (just trying to get the services to stop in the correct order):
    $MainServiceName = "SNMP"
    $ServiceInput = ""
    $CurrentService = ""
    $Service = ""
    function Custom-Stop-Service ($ServiceInput)
    Write-Host "Name of `$ServiceInput: $($ServiceInput.Name)"
    Write-Host "Number of dependents: $($ServiceInput.DependentServices.Count)"
    If ($ServiceInput.DependentServices.Count -gt 0)
    ForEach ($Service in $ServiceInput.DependentServices)
    Write-Host "Dependent of $($ServiceInput.Name): $($Service.Name)"
    If ($Service.Status -eq "Running")
    Write-Host "$($Service.Name) is running."
    $CurrentService = Get-Service -Name $Service.Name
    Custom-Stop-Service $CurrentService
    Write-Host "Stopping service $($CurrentService.Name)"
    Stop-Service -Name $CurrentService.Name -Force
    Else
    Write-Host "$($Service.Name) is stopped."
    Else
    Write-Host "Stopping service $($ServiceInput.Name)"
    Stop-Service -Name $ServiceInput.Name
    $MainService = Get-Service -Name $MainServiceName
    If ($MainService.Status -eq "Stopped")
    Write-Host "Service $($MainService.Name) is already stopped."
    Else
    Custom-Stop-Service $MainService
    However, it doesn't work like I expect.  Firstly, it never attempts to stop the SNMP service itself.  Secondly while it does seem to stop all the dependents of SNMP correctly, it tries to stop CqMgHost twice.  Here is the output:
    PS C:\Scripts> .\restart_service.ps1
    Name of $ServiceInput: SNMP
    Number of dependents: 4
    Dependent of SNMP: CqMgHost
    CqMgHost is running.
    Name of $ServiceInput: CqMgHost
    Number of dependents: 0
    Stopping service CqMgHost
    WARNING: Waiting for service 'HP Insight Foundation Agents (CqMgHost)' to finish stopping...
    WARNING: Waiting for service 'HP Insight Foundation Agents (CqMgHost)' to finish stopping...
    WARNING: Waiting for service 'HP Insight Foundation Agents (CqMgHost)' to finish stopping...
    WARNING: Waiting for service 'HP Insight Foundation Agents (CqMgHost)' to finish stopping...
    Stopping service CqMgHost
    Dependent of SNMP: CqMgStor
    CqMgStor is running.
    Name of $ServiceInput: CqMgStor
    Number of dependents: 1
    Dependent of CqMgStor: CqMgHost
    CqMgHost is stopped.
    Stopping service CqMgStor
    Dependent of SNMP: CqMgServ
    CqMgServ is running.
    Name of $ServiceInput: CqMgServ
    Number of dependents: 1
    Dependent of CqMgServ: CqMgHost
    CqMgHost is stopped.
    Stopping service CqMgServ
    WARNING: Waiting for service 'HP Insight Server Agents (CqMgServ)' to finish stopping...
    WARNING: Waiting for service 'HP Insight Server Agents (CqMgServ)' to finish stopping...
    Dependent of SNMP: CpqNicMgmt
    CpqNicMgmt is running.
    Name of $ServiceInput: CpqNicMgmt
    Number of dependents: 1
    Dependent of CpqNicMgmt: CqMgHost
    CqMgHost is stopped.
    Stopping service CpqNicMgmt
    Can someone suggest a different script or changes to my script so that it will do what I want?  I know that "Stop-Service -Name SNMP -Force" will work but there are two problems with this: 1) it doesn't record the stop events for the dependents in the
    Event Viewer and 2) it doesn't work in reverse ("Start-Service -Name SNMP -Force" nor "Restart-Service -Name SNMP -Force" restart the main service and the other services that depend on SNMP that were stopped).
    I'm a little surprised that Restart-Service doesn't behave like the restart function in the Services MMC does, where it easily and reliably handles the stops and starts of not only the service itself, but dependent services and also properly does event logging.

    I decided to try to understand why you see layers of dependencies.  I found that on WS2008 R2 HP managemnet does have a second layer.  It does not incluse anything but subservices from HP>  VSC is not  a dependency and, from my research,
    should not ever be a dependency.  Of course this does not stop someone from making it a dependency which could create issues.
    Here is a recursive function that will display all dependencies of any service or all services,
    The code returns the service names in order and can be used to restart all services in dependent order.
    function Get-Depends{
    [CmdLetBinding()]
    Param(
    $servicename='SNMP',
    $level = 0,
    [switch]$infoonly
    try{
    Write-Verbose $($("`t" * $level)+$servicename)
    $servicename
    $services=get-service $servicename -ea stop | where{$_.dependentservices}|select -expand dependentservices
    if($services){
    $services | %{Get-Depends $($_.Name) ($level+1) }
    catch{
    $_
    $depends=Get-Depends -v
    The verbose switch displays a hierarchical display of names to ilustrate the dependencies.
    jv

  • Get the daily incremental search crawl information using PowerShell script

    Dear Friends ,
        I want to get the daily incremental search crawl information using PowerShell script . I need this information into CSV or txt format . Can you please help me with this.
    valmiki

    Hi
    I  have got the below script which worked .
    ## SharePoint Reference
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration")
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.Search.Administration")
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.Search")
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
    function global:Get-CrawlHistory($url)
    trap [Exception] {
    write-error $("ERROR: " + $_.Exception.GetType().FullName);
      write-error $("ERROR: " + $_.Exception.Message);
      continue;  
    $s =
    new-Object Microsoft.SharePoint.SPSite($url);
    $c = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($s);
    $h =
    new-Object Microsoft.Office.Server.Search.Administration.CrawlHistory($c);
    Write-OutPut $h.GetCrawlHistory();
    $s.Dispose();
    Get-CrawlHistory
    -url  http://your_site_url/
      |
    Export-CsvF:\temp\search.csv
    valmiki

  • Powershell script to change the a column value of all documents in a site.

    Hi,
    I need a powershell script to change the value of a column (a site column which has been added to all document libraries) in all documents in a site,
    For example: 
    -column 1 is a site column added to all libraries
    the value of column 1 of all documents under this site: http://intranet.doman/ex1 should be equal to V1
    the value of column 1 of all documents under this site: http://intranet.doman/ex2 should be equal to V2
    So, if I can write a powershell script to change the value of all documents in a site, I can modify it for different site that I have and run it for each of them individually,

    cls
    # Is dev version?
    $dev = $false
    # Configuration
    $termStore = "Managed Metadata Service"
    $group = "G1"
    $subjectMatterTermSetName = "Subject Matter"
    # Check if SharePoint Snapin is loaded
    if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
         Add-PSSnapin Microsoft.SharePoint.PowerShell
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Taxonomy") | Out-Null
    function GetTermStore($site, $termStore, $group, $termSet) {    
        $session = New-Object Microsoft.SharePoint.Taxonomy.TaxonomySession($site)
        $termStore = $session.TermStores[$termStore]
        $group = $termStore.Groups[$group]
        $termSet = $group.TermSets[$termSet]
        return $termSet
    if($dev) {
        Write-Host "Running DEV version..."
        $webUrl = "http://Site1"   
        $libraryName = "L1"
        $subjectMatter = "C1"
    } else {
        $webUrl = Read-Host "Enter Site URL" 
        $libraryName = Read-Host "Enter Document Library name"
    $subjectMatter = Read-Host "Enter Subject Matter"
    try {
        $web = Get-SPWeb $webUrl
        $site = $web.Site
        $library = $web.Lists[$libraryName]
        $items = $library.GetItems()
        $subjectMatterTermSet = GetTermStore $site $termStore $group $subjectMatterTermSetName
        $subjectMatterTerm = $subjectMatterTermSet.GetTerms($subjectMatter,$true) | select -First 1
        foreach($item in $items) {
            if([string]::IsNullOrEmpty($item["Subject Matter"])) {     
                #Write-Host "Filename: $filename / Keywords: $keywords / Subject Matter: $subjectMatter / Document Type: $documentType"        
                Write-Host "Updating $($item["ows_FileLeafRef"])..."           
                # Set Subject Matter column
                $subjectMatterField = [Microsoft.SharePoint.Taxonomy.TaxonomyField]$item.Fields["Subject Matter"]
                $subjectMatterField.SetFieldValue($item,$subjectMatterTerm)
                # Update Item
                $item.SystemUpdate()
    catch
        $ErrorMessage = $_.Exception.Message
        Write-Host "Something went wrong. Error: $ErrorMessage" -ForegroundColor Red

  • Powershell Script to manage document library

    Hi,
    I would like to write a powershell script that will be run as a job in the task scheduler on a daily basis. The  idea is to delete documents or folders from a particular folder in the document library that are created 30 days ago.
    Can anyone help me with this script?

    Hi - I think you can perform this OOB using retention policy
    http://blogs.msdn.com/b/ecm/archive/2011/10/12/policy-and-retention-in-sharepoint-server-2010.aspx
    http://blogs.msdn.com/b/mvpawardprogram/archive/2011/10/03/applying-document-retention-in-sharepoint-2010.aspx
    -prs

  • Powershell script to search a network drive for .mdb files and export them to CSV file

    Hello all,
    I'm trying to search one of our network drives for old .mdb files, I want to write the name, location and date last modified to a csv file.
    Get-WmiObject -Class CIM_DataFile -Filter "Drive='S:' And Extension='mdb'
     AND ObjFile.drive
     AND objFile.FileName
     AND objFile.FileSize
     AND objFile.LastWriteTime" |
    Export-CSV c:\mdb_search\mdbfiles.csv\
    Obviously this isn't working or I wouldn't be posting.  I've tried many different examples from the net with no joy for now.
    Thanks for any help you can offer.

    Thanks, that did the job.
    Cheers, you're welcome.
    How do I get the powershell cursor to return to C:> ?
    Should I use "exit" or "break" ?
    Neither, the console will return to a prompt when the search has been completed.
    Don't retire TechNet! -
    (Don't give up yet - 13,225+ strong and growing)

Maybe you are looking for