My approach is to get the latest ModifyTimeStamp after scanning on all DC's. The scenario in my code is:
First, I scan on the PDC to get the distinguishedName values, and after that I scan on all DC's also to get distinguishedName values, if they are -eq to each other, it will print the ModifyTimeStamp which means all ModifyTimeStamp values on each DC's will be stored in an arraylist. The arraylist will print the maximum values then on. As the following:
$TrustedDomain = "test.com"
$context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext("domain",$TrustedDomain)
$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($context)
$PDC = $D.PdcRoleOwner
$ADSearch = New-Object System.DirectoryServices.DirectorySearcher
$ADSearch.SearchRoot ="LDAP://$PDC"
$ADSearch.SearchScope = "subtree"
$ADSearch.PageSize = 100
$ADSearch.Filter = "(&(objectCategory=person)(objectClass=user))"
foreach($pro in $properies)
{
$ADSearch.PropertiesToLoad.add($pro)| out-null
}
$userObjects = $ADSearch.FindAll()
$dnarr = New-Object System.Collections.ArrayList
Function modiScan{
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize = 100
$Searcher.SearchScope = "subtree"
$Searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
$Searcher.PropertiesToLoad.Add("distinguishedName")|Out-Null
$Searcher.PropertiesToLoad.Add("modifyTimeStamp")|Out-Null
forEach ($users In $userObjects)
{
$DN = $users.Properties.Item("distinguishedName")[0]
$dnarr.add($DN)|Out-Null
}
#$dnarr
foreach($dnn in $dnarr){
$lastmd = New-Object System.Collections.ArrayList
ForEach ($DC In $D.DomainControllers){
$Server = $DC.Name
$Base = "LDAP://$Server/"+$dnn
$Searcher.SearchRoot = $Base
$Results2 = $Searcher.FindAll()
ForEach ($Result2 In $Results2)
{
$DN2 = $Result2.Properties.Item("distinguishedName")[0]
if($DN2 -eq $dnn){
$modi = $Result2.Properties.Item("modifyTimeStamp")[0]
$lastmd.Add($modi)|Out-Null
}
}
}
$lastModi = ($lastmd |measure -max).maximum
if($lastModi -ne $null){
$lastModi = $lastModi.ToString("yyyy/MM/dd")
}
else{
$lastModi = "N/A"
}
$lastModi
}
}
modiScan
The error I've got is:
Exception calling "FindAll" with "0" argument(s): "Unknown error (0x80005000)"
At C:\Users\Ender\trustedScan.ps1:40 char:21
+ $Results2 = $Searcher.FindAll()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : COMException
I have executed on current Domain it worked like a charm. But when I try to put a trusted domain, it throws me that error.
Related
I am creating views for multiple libraries in SharePoint. I am able to create view from below code successfully for one library. But I am stuck when I run the code in a loop. Below is my code
Code
Add-PSSnapin "Microsoft.SharePoint.Powershell" -EA SilentlyContinue
$subSiteURL = #("http://test.test.com/departments/Collections", "http://test.test.com/departments/Events")
$listName = #("Collections","Events")
for ($i=0; $i -lt $subSiteURL.length; $i++) {
$SPWeb = Get-SPWeb $subSiteURL[$i]
$ListName = $listName[$i]
$List = $SPWeb.Lists[$ListName]
$ViewTitle = "WebPart View"
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("DocIcon")
$viewFields.Add("LinkFilenameNoMenu")
$viewQuery = "<GroupBy Collapse='FALSE' GroupLimit='100'> <FieldRef Name='Category' Ascending='True'/> <FieldRef Name='Sub_x002d_Category' Ascending='True'/> </GroupBy> <OrderBy> <FieldRef Name='FileLeafRef' /></OrderBy> <Where><Or><Leq><FieldRef Name='Start_x0020_Date' /><Value Type='DateTime'>[Today]</Value></Leq><And><Geq><FieldRef Name='Expiry_x0020_Date' /><Value Type='DateTime'>[Today]</Value></Geq><Eq><FieldRef Name='Always_x0020_Display' /><Value Type='Boolean'>Yes</Value></Eq></And></Or></Where>"
$viewRowLimit = 999
$viewPaged = $false
$viewDefaultView = $false
$newView = $list.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
$newView.TabularView = $False
$newView.Scope = "Recursive"
$newView.Update()
}
Error
You cannot call a method on a null-valued expression.
At D:\\CreateDocLibrariesViews.ps1:24 char:28
+ $newView = $list.Views.Add <<<< ($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
+ CategoryInfo : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Try below script:
Add-PSSnapin "Microsoft.SharePoint.Powershell" -EA SilentlyContinue
$subSiteURL = #("http://sp", "http://sp:12001")
$listNames = #("MyDoc")
for ($i=0; $i -lt $subSiteURL.length; $i++) {
Write-Host $subSiteURL[$i]
$SPWeb = Get-SPWeb $subSiteURL[$i]
for ($j=0; $j -lt $listNames.length; $j++) {
$ListName = $listNames[$j]
Write-Host $ListName
$List = $SPWeb.Lists[$ListName]
$ViewTitle = "WebPart View"
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("DocIcon")
$viewFields.Add("LinkFilenameNoMenu")
$viewQuery = "<GroupBy Collapse='FALSE' GroupLimit='100'> <FieldRef Name='Category' Ascending='True'/></GroupBy> <OrderBy> <FieldRef Name='FileLeafRef' /></OrderBy>"
$viewRowLimit = 999
$viewPaged = $false
$viewDefaultView = $false
$newView = $list.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
$newView.TabularView = $False
$newView.Scope = "Recursive"
$newView.Update()
}
}
Write-Host "done"
I have following powershell script which should update my windows OS everytime I run it. Therefore I use the given windows API in order to search, download and install the updates. But somehow only searching for them actually works.
This is my script:
$global:scriptpath = $MyInvocation.MyCommand.Path
$global:dir = Split-Path $scriptpath
$global:logfile = "$dir\updatelog.txt"
write-host " Searching for updates..."
$session = New-Object -ComObject Microsoft.Update.Session
$searcher = $session.CreateUpdateSearcher()
$result = $searcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")
if ($result.Updates.Count -eq 0) {
Write-Host "No updates to install"
} else {
$result.Updates | Select Title
}
$downloads = New-Object -ComObject Microsoft.Update.UpdateColl
foreach ($update in $result){
try {
$update.AcceptEula()
$Null = $downloads.Add($update)
} catch {}
}
$count = $result.Updates.Count
write-host ""
write-host "There are $($count) updates available."
write-host ""
read-host "Press Enter to download\install updates"
$downloader = $session.CreateUpdateDownLoader()
$downloader.Updates = $downloads
$downloader.Download()
$installs = New-Object -ComObject Microsoft.Update.UpdateColl
foreach ($update in $result.Updates){
if ($update.IsDownloaded){
$installs.Add($update)
}
}
$installer = $session.CreateUpdateInstaller()
$installer.Updates = $installs
$installresult = $installer.Install()
$installresult
But I get following error:
Exception calling "Download" with "0" argument(s): "Exception from HRESULT: 0x80240024"
+ $downloader.Download()
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
Somehow this line: $downloader.Updates = $downloads is not executed, but I don't know why. I also already tried running the script as an admin, didn't work either.
That error code is the WU_E_NO_UPDATE, described here. Basically it says that the Updates collection is not set or empty.
I have a script which I think is most of the way to being able to grab IE history for all of the users on a machine. My problem is it doesn't work for users other than myself because I get a permissions error when attempting open the folder. Does anyone have any ideas how I can fix the permissions problem?
I'm running this script on a Windows 2012r2 machine and I am an administrator on the box.
Thanks!
function Get-History
{
param
(
[string]$userName
)
$shell = New-Object -ComObject Shell.Application
if($username)
{
$users = $username
}
else
{
$users = Get-ChildItem C:\Users
}
if((([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")))
{
Foreach($user in $users)
{
$user = Split-Path $user -leaf
try
{
$ErrorActionPreference = 'Stop'
$hist = $shell.NameSpace("C:\Users\$user\AppData\Local\Microsoft\Windows\History")
}
catch
{
continue
}
$folder = $hist.Self
#$folder.Path
if($hist){
$hist.Items() | foreach {
#""; ""; $_.Name
if ($_.IsFolder) {
$siteFolder = $_.GetFolder
$siteFolder.Items() | foreach {
$site = $_
#""; $site.Name
if ($site.IsFolder) {
$pageFolder = $site.GetFolder
$pageFolder.Items() | foreach {
$url = $pageFolder.GetDetailsOf($_,0)
$date = $pageFolder.GetDetailsOf($_,2)
#"$user`: $date visited $url"
#Write-Output ("$user,$date,`"$url`"" | ConvertFrom-Csv)
New-Object -TypeName PSObject -Property #{
user=$user;
date = $date;
url = $url
}
}
}
}
}
}
}
}
}
else
{
Write-Host "Not Admin"
}
}
If I run just the small snippet:
$shell = New-Object -ComObject Shell.Application
$hist = $shell.NameSpace("C:\Users\MyOwnUsername\AppData\Local\Microsoft\Windows\History")
Then I successfully assign the $hist variable as a System.__ComObject
But if I run:
$shell = New-Object -ComObject Shell.Application
$hist = $shell.NameSpace("C:\Users\SomeOtherUser\AppData\Local\Microsoft\Windows\History")
I get:
Exception calling "NameSpace" with "1" argument(s): "Unspecified error (Exception from HRESULT: 0x80004005 (E_FAIL))"
At line:3 char:1
+ $hist = $shell.NameSpace("C:\Users\SomeOtherUser\AppData\Local\Microsoft\Windows\History ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
Full Disclosure: it's a slight modification of the script at this blog post
I never solved the permissions problem. I changed strategy to use BrowsingHistoryViewer by Nirsoft.
$execPath = "C:\BrowsingHistoryView.exe"
$computers = 'computer1','computer2','computer3','computer4'
$outPath = "c:\"
$computers |
ForEach-Object{ `
Start-Process $execPath `
-argumentList "/HistorySource 3",
"/HistorySourceFolder ""\\$_\c$\Users""",
"/scomma ""$outpath\history_$_.txt"""
}
1) Here's my schema:
{
"_id" : ObjectId("53f4db1d968166157c2d57ce"),
"init" : "SJ",
"name" : "Steve Jobs",
"companies" : [
{
"_id" : ObjectId("53f4db1d968166157c2d57cf"),
"ticker" : "AAPL",
"compname" : "Apple"
},
{
"_id" : ObjectId("53f4db1d968166157c2d57d0"),
"ticker" : "MSFT",
"compname" : "Microsoft"
},
{
"_id" : ObjectId("53f4db1d968166157c2d57d1"),
"ticker" : "ABC",
"compname" : "iTunes"
},
{
"_id" : ObjectId("53f4db1d968166157c2d57d2"),
"ticker" : "DEF",
"compname" : "iPad Mini"
}
]
}
I'm trying to get a list of compnames, using Powershell & MongoDB. Here's what I have so far:
$databaseName = "CompanyInfo"
$collectionName = "comps"
$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017"
$server = $client.GetServer()
$database = $server.GetDatabase($databaseName)
$collection = $database.GetCollection($collectionName)
$query['init'] = "SJ"
$results = $collection.FindOne($query)
foreach ($result in $results) {
write-host $result["companies.ticker"] /// Doesn't show me any records
}
This doesn't show me any records. How can I display companies.ticker info where init = "SJ"?
2) Btw, I get the following error after
$query['init'] = "SJ"
error
Cannot index into a null array.
At line:9 char:1
+ $query['init'] = "SJ"
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
Any ideas as to why? I only have the MongoDB's standard index, which is on "_id", nothing else. My powershell script still works but I'm curious as to why I get that error.
[UPDATE Part 2] Thanks to #arco444, I no longer get error in part 2. Here's my revised code:
$query = #{'init' = "SJ"}
$collection.FindOne([MongoDB.Driver.QueryDocument]$query)
But I actually need help with part 1 - which is to display only the company tickers for a particular init. Any ideas on that one?
[ANSWER Part 1] Thanks again to #arco444 for directing me to the right path. After some tinkering around, I figured out what I missed. Here's my updated code:
$databaseName = "CompanyInfo"
$collectionName = "comps"
$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017"
$server = $client.GetServer()
$database = $server.GetDatabase($databaseName)
$collection = $database.GetCollection($collectionName)
$query = new-object MongoDB.Driver.QueryDocument("init","SJ") /// Updated
$results = $collection.FindOne($query)
foreach ($result in $results["companies"]) { /// Updated
write-host $result["ticker"] /// Updated
}
From reading the MongoDB documentation, it looks like you need to initialise the query object properly first. Try this:
$query = new-object MongoDB.Driver.QueryDocument("init","SJ")
$results = $collection.FindOne($query)
Here's my updated code:
$databaseName = "CompanyInfo"
$collectionName = "comps"
$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://localhost:27017"
$server = $client.GetServer()
$database = $server.GetDatabase($databaseName)
$collection = $database.GetCollection($collectionName)
$query = new-object MongoDB.Driver.QueryDocument("init","SJ") /// Updated
$results = $collection.FindOne($query)
foreach ($result in $results["companies"]) { /// Updated
write-host $result["ticker"] /// Updated
}
So when I use your query procedure with
$mongoDbDriverPath = 'D:\mongo\driver\'
$mongoServer = 'myserver:27000'
Add-Type -Path "$($mongoDbDriverPath)MongoDB.Bson.dll"
Add-Type -Path "$($mongoDbDriverPath)MongoDB.Driver.dll"
$databaseName = 'Tickets'
$collectionName = 'MongoUserTicket'
$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://$mongoServer"
$server = $client.GetServer()
$database = $server.GetDatabase($databaseName)
$collection = $database.GetCollection($collectionName)
$query = new-object Mongodb.driver.querydocument('Id','5')
$query2 = New-object Mongodb.driver.querydocument('Type','User')
$results = #()
foreach($item in $collection.Find($query))
{
$results += $item
}
I get unexpected results for the query:
When piping to Get member for results I get this:
TypeName: MongoDB.Bson.BsonElement
Name MemberType Definition
---- ---------- ----------
Clone Method MongoDB.Bson.BsonElement Clone()
CompareTo Method int CompareTo(MongoDB.Bson.BsonElement other), int IComparable[BsonElement].CompareTo(MongoDB.Bson.BsonElement other)
DeepClone Method MongoDB.Bson.BsonElement DeepClone()
Equals Method bool Equals(MongoDB.Bson.BsonElement rhs), bool Equals(System.Object obj), bool IEquatable[BsonElement].Equals(MongoDB.Bson.BsonElement other)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Name Property string Name {get;}
Value Property MongoDB.Bson.BsonValue Value {get;set;}
When entering $results on the shell prompt I get the data I expect:
$results
Name Value
---- -----
Id 5
AccessToken
CreatedOn 2013-09-27T22:05:52.246Z
TokenExpiration 2013-09-27T22:20:52.246Z
RefreshTokenExpiration 2013-09-28T22:05:52.246Z
ProfileToken BsonNull
Type User
Id 5
AccessToken
CreatedOn 2013-09-27T23:42:28.492Z
TokenExpiration 2013-09-27T23:57:28.492Z
RefreshTokenExpiration 2013-09-28T22:06:04.071Z
ProfileToken BsonNull
Type User
here is what allowed me to get an object that i could operate on:
$results = #()
foreach($item in $collection.Find($query))
{
$props = #{}
$item | foreach { $props[ $_.name ] = $_.value }
$pso = [pscustomobject]$props
$results += $pso
}
full code:
$mongoDbDriverPath = 'D:\mongo\driver\'
$mongoServer = 'myserver:27000'
Add-Type -Path "$($mongoDbDriverPath)MongoDB.Bson.dll"
Add-Type -Path "$($mongoDbDriverPath)MongoDB.Driver.dll"
$databaseName = 'Tickets'
$collectionName = 'MongoUserTicket'
$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList "mongodb://$mongoServer"
$server = $client.GetServer()
$database = $server.GetDatabase($databaseName)
$collection = $database.GetCollection($collectionName)
$query = new-object Mongodb.driver.querydocument('Id','5')
$query2 = New-object Mongodb.driver.querydocument('Type','User')
$results = #()
foreach($item in $collection.Find($query))
{
$props = #{}
$item | foreach { $props[ $_.name ] = $_.value }
$pso = [pscustomobject]$props
$results += $pso
}
$results
I posted this script the other day in an effort to discover a good way to change file extensions when "saving as." I had the problem licked, but as of this morning, the script will not run without errors. Here's the error message I'm getting:
Processing : C:\users\xxx\Desktop\ht\Automatic_Post-Call_Survey.htm
Exception calling "SaveAs" with "16" argument(s): "This is not a valid file name.
Try one or more of the following:
* Check the path to make sure it was typed correctly.
* Select a file from the list of files and folders."
At C:\users\xxx\Desktop\hd.ps1:11 char:20
+ $opendoc.saveas <<<< ([ref]"$docpath\$doc.FullName.doc", [ref]$saveFormat);
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
if "16" is the error code, that represents an inability to delete the directory...but it doesn't appear as if I'm asking for that at all--unless there's some default parameter in place somewhere. I'm pretty much baffled.anyone have any other ideas I can try out?
$docpath = "c:\users\xxx\desktop\do"
$htmPath = "c:\users\xxx\desktop\ht"
$srcfiles = Get-ChildItem $htmPath -filter "*.htm*"
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatDocument");
$word = new-object -comobject word.application
$word.Visible = $False
$filename = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
function saveas-document {
$opendoc = $word.documents.open($doc.FullName);
$opendoc.saveas([ref]"$docpath\$filename", [ref]$saveFormat);
$opendoc.close();
}
ForEach ($doc in $srcfiles) {
Write-Host "Processing :" $doc.FullName
saveas-document
$doc = $null
}
$word.quit();
this should do what do you need, but is not the best design :)
$docpath = "c:\users\xxx\desktop\do"
$htmPath = "c:\users\xxx\desktop\ht"
$srcfiles = Get-ChildItem $htmPath -filter "*.htm*"
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatDocument");
$global:word = new-object -comobject word.application
$word.Visible = $False
#$filename = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
function saveas-document ($docs) {
$opendoc = $word.documents.open($docs);
$savepath = $docs -replace [regex]::escape($htmPath),"$docpath"
$savepath = $savepath -replace '\.html*', '.doc'
$opendoc.saveas([ref]"$savepath", [ref]$saveFormat);
$opendoc.close();
}
ForEach ($doc in $srcfiles) {
Write-Host "Processing :" $doc.FullName
saveas-document -doc $doc.FullName
$doc = $null
}
$word.quit();