Powershell Script to obtain current members of a Group
Good morning. Sorry for my English.
I would like to change the answer obtained by a script.
Today the scrip that I have, give me the following response:
Server 1
Group 1
User 1 User 2 User 3
Server 2
Group 1
User 1 User 2 User 3
I need the answer is something like:
Server 1
Group 1 User
1
Server 1
Group 1 User
2
Server 1
Group 1 User
3
Server 2
Group 1 User
1
Server 2
Group 1 User
2
Server 2
Group 1 User
3 ...Etc
What change I had to do in the script below to that he gave me this level of response?
Import-Module ActiveDirectory
$Result = @()
foreach($server in (gc .\servers.txt)){
$computer = [ADSI](”WinNT://” + $server + “,computer”)
$Group = $computer.psbase.children.find(”Remote Desktop Users”)
$a=getAdmins
function getAdmins
{$members = ($Group.psbase.invoke(”Members”) | %{$_.GetType().InvokeMember(”Adspath”, ‘GetProperty’, $null, $_, $null)}) -replace ('WinNT://DOMAIN/' + $server + '/'), '' -replace ('WinNT://DOMAIN/', 'DOMAIN\') -replace ('WinNT://', '')
$members}
$Result += Write-Output "SERVER: $server $a"
$Result > C:\Groups\RemoteDesktopUsers.txt
Grateful.
Hi,
So, there is a way from a script to obtain from a list of servers in a *.txt the users and groups from the groups Remote Desktop Users or Domain Admins?
I need the answer is something like:
Server 1
Group 1 User
1
Server 1
Group 1 User
2
Server 1
Group 1 User
3
Server 2
Group 1 User
1
Server 2
Group 1 User
2
Server 2
Group 1 User
3 ...Etc
Grateful.
Similar Messages
-
Powershell script to Get members of AD group members with first, last, email address
I'm running a powershell script to retrieve AD users from a specific AD group and pipe specific attributes to a csv file. The script is working perfectly except for one detail. I want the script to ignore any users who have a null value in any of the values
I'm piping to the spreadsheet. Meaning that if any of the users found in the queried groups have a null value in the attributes givenname, sn or mail, ignore the user and do not pipe to the csv.
Get-ADGroupMember -identity adgroup -recursive | get-adobject -Properties givenname,sn,mail | select givenname,sn,mail |export-csv -path c:\powershell\groupmembers.csv
–NoTypeInformationHi,
You can pipe your user objects through ForEach-Object and then use if to verify all three properties exist. If so, output the object. If not, move to the next object. After you've processed all user objects, then pipe into Export-Csv.
EDIT: See below.
Don't retire TechNet! -
(Don't give up yet - 13,225+ strong and growing) -
How to Parse this XML File and require below mentioned value as output using powershell script
Need values for below as an output for below xml file so help me with the script:
Under Criteria Tag-
TimeStamp Display Value
OID corresponding to display value for nodes "Criterion"
Under Report Body Tag--
name in Report Section and OID value
<?xml version="1.0" encoding="UTF-8"?>
<ReportOutput>
<ReportHead>
<Report name="Execution Action" type="detailedchanges_rpt">
<Description></Description>
</Report>
<Criteria>
<TimestampCriterion name="date" displayvalue="08/10/14 23:08">
<Timestamp displayvalue="08/10/14 23:08">1412780929000</Timestamp>
</TimestampCriterion>
<MatchCriterion name="approvalId" displayvalue="Not applied" operator="contains" />
<MatchCriterion name="promotionComment" displayvalue="Not applied" operator="contains" />
<SelectCriterion name="changeWindow" displayvalue="Not applied" />
<SelectCriterion name="auditEvents" displayvalue="(Any)">
<String>auditEventAny</String>
</SelectCriterion>
<SelectCriterion name="attributeDisplay" displayvalue="Changed attributes">
<String>changed</String>
</SelectCriterion>
<SelectCriterion name="versionCompare" displayvalue="Version with current baseline">
<String>disabled</String>
</SelectCriterion>
<BooleanCriterion name="showContentDiff" displayvalue="No">
<Boolean value="false" />
</BooleanCriterion>
<BooleanCriterion name="displayUsers" displayvalue="No">
<Boolean value="false" />
</BooleanCriterion>
<BooleanCriterion name="displayPackages" displayvalue="No">
<Boolean value="false" />
</BooleanCriterion>
<BooleanCriterion name="displayCustomProperties" displayvalue="No">
<Boolean value="false" />
</BooleanCriterion>
<BooleanCriterion name="strictPackageMatch" displayvalue="No">
<Boolean value="false" />
</BooleanCriterion>
<BooleanCriterion name="displayCriteriaAtEnd" displayvalue="No">
<Boolean value="false" />
</BooleanCriterion>
<SelectCriterion name="elementExists" displayvalue="Not applied" />
<IntegerCriterion name="maxLinesPerBlock" displayvalue="10">
<Integer>10</Integer>
</IntegerCriterion>
<NodesCriterion name="nodes" displayvalue="TripwireENT.demo.net">
<OID>-1y2p0ij32e8bw:-1y2p0ij32e7cu</OID>
</NodesCriterion>
<MatchCriterion name="nodeName" displayvalue="Not applied" operator="contains" />
<CustomPropertiesCriterion name="nodeProps" displayvalue="Not applied" />
<RulesCriterion name="rules" displayvalue="Critical System Files">
<OID>-1y2p0ij32e7q2:-1y2p0ij31snh6</OID>
</RulesCriterion>
<MatchCriterion name="ruleName" displayvalue="Not applied" operator="contains" />
<MatchCriterion name="elementName" displayvalue="Not applied" operator="contains" />
<CustomPropertiesCriterion name="elementProps" displayvalue="Not applied" />
<CustomPropertiesCriterion name="versionProps" displayvalue="Not applied" />
<AttributesCriterion name="attributes" displayvalue="Not applied">
<Integer name=".missingImpliesFailure">1</Integer>
</AttributesCriterion>
<ContentCriterion name="content" displayvalue="Not applied" />
<MatchCriterion name="auditEventUserName" displayvalue="Not applied" operator="contains" />
<IntegerCriterion name="changeType" displayvalue="Added, Modified, Removed">
<Integer>7</Integer>
</IntegerCriterion>
<SeverityRangeCriterion name="severity" displayvalue="1 - 10000">
<Integer name="min">1</Integer>
<Integer name="max">10000</Integer>
</SeverityRangeCriterion>
<BooleanCriterion name="currentVersionsOnly" displayvalue="Yes">
<Boolean value="true" />
</BooleanCriterion>
<TimeRangeCriterion name="timeRange" displayvalue="All time" />
<PackagesCriterion name="packages" displayvalue="Not applied" />
<SortCriterion name="sortNodes" displayvalue="Name, ascending" isascending="true">
<String>name</String>
</SortCriterion>
<SortCriterion name="sortRules" displayvalue="Name, ascending" isascending="true">
<String>name</String>
</SortCriterion>
<SortCriterion name="sortElements" displayvalue="Name, ascending" isascending="true">
<String>name</String>
</SortCriterion>
<SortCriterion name="sortVersions" displayvalue="Date, descending" isascending="false">
<String>date</String>
</SortCriterion>
</Criteria>
</ReportHead>
<ReportBody>
<ReportSection name="TripwireENT.demo.net" category="node">
<OID>-1y2p0ij32e8bw:-1y2p0ij32e7cu</OID>
<String name="typeName">Windows Server</String>
<ReportSection name="Critical System Files" category="rule">
<OID>-1y2p0ij32e7q2:-1y2p0ij31snh6</OID>
<String name="typeName">Windows File System Rule</String>
<ReportSection name="C:\Temp" category="element">
<OID>-1y2p0ij32e8dr:-1y2p0ij32e586</OID>
<ReportSection name="08/10/14 22:48" category="version">
<OID>-1y2p0ij32e8du:-1y2p0ij32e3ho</OID>
<Integer name="changeType">1</Integer>
<String name="changeTypeName">Added</String>
<Integer name="severity">10000</Integer>
<String name="severityName">High</String>
<Timestamp name="changeTime" displayvalue="08/10/14 22:48">1412779682000</Timestamp>
<String name="approvalId"></String>
<ReportSection name="attributes" category="attributes">
<ReportSection name="DACL" category="added">
<String name="observed">Inherits Entries: true
NT AUTHORITY\SYSTEM, Access Allowed:
Standard rights:
Full Control
Modify
Read & Execute
List Folder Contents
Read
Write
Delete
Read Control
Write DAC
Write Owner
Synchronize
Specific rights:
Full Control
Traverse Folder / Execute File
List Folder / Read Data
Read Attributes
Read Extended Attributes
Create Files / Write Data
Create Folders / Append Data
Write Attributes
Write Extended Attributes
Directory Delete Child
Read Permissions
Change Permissions
Take Ownership
Header flags:
Object Inherit
Container Inherit
Inherited
BUILTIN\Administrators, Access Allowed:
Standard rights:
Full Control
Modify
Read & Execute
List Folder Contents
Read
Write
Delete
Read Control
Write DAC
Write Owner
Synchronize
Specific rights:
Full Control
Traverse Folder / Execute File
List Folder / Read Data
Read Attributes
Read Extended Attributes
Create Files / Write Data
Create Folders / Append Data
Write Attributes
Write Extended Attributes
Directory Delete Child
Read Permissions
Change Permissions
Take Ownership
Header flags:
Object Inherit
Container Inherit
Inherited
BUILTIN\Users, Access Allowed:
Standard rights:
Read & Execute
List Folder Contents
Read
Read Control
Synchronize
Specific rights:
Traverse Folder / Execute File
List Folder / Read Data
Read Attributes
Read Extended Attributes
Read Permissions
Header flags:
Object Inherit
Container Inherit
Inherited
BUILTIN\Users, Access Allowed:
Specific rights:
Create Folders / Append Data
Header flags:
Container Inherit
Inherited
BUILTIN\Users, Access Allowed:
Specific rights:
Create Files / Write Data
Header flags:
Container Inherit
Inherited
CREATOR OWNER, Access Allowed:
Generic rights:
Generic All
Specific rights:
Full Control
Traverse Folder / Execute File
List Folder / Read Data
Read Attributes
Read Extended Attributes
Create Files / Write Data
Create Folders / Append Data
Write Attributes
Write Extended Attributes
Directory Delete Child
Read Permissions
Change Permissions
Take Ownership
Header flags:
Object Inherit
Container Inherit
Inherit Only
Inherited
</String>
</ReportSection>
<ReportSection name="Group" category="added">
<String name="observed">TRIPWIREENT\None</String>
</ReportSection>
<ReportSection name="Owner" category="added">
<String name="observed">BUILTIN\Administrators</String>
</ReportSection>
<ReportSection name="Read-Only" category="added">
<String name="observed">false</String>
</ReportSection>
<ReportSection name="SACL" category="added">
<String name="observed">(null)</String>
</ReportSection>
<ReportSection name="Type" category="added">
<String name="observed">Directory</String>
</ReportSection>
</ReportSection>
</ReportSection>
</ReportSection>
<ReportSection name="C:\Windows\System32\drivers\etc\hosts" category="element">
<OID>-1y2p0ij32e8dr:-1y2p0ij32e4kp</OID>
<ReportSection name="08/10/14 23:08" category="version">
<OID>-1y2p0ij32e8du:-1y2p0ij32e3hk</OID>
<Integer name="changeType">2</Integer>
<String name="changeTypeName">Modified</String>
<Integer name="severity">10000</Integer>
<String name="severityName">High</String>
<Timestamp name="changeTime" displayvalue="08/10/14 23:08">1412780929000</Timestamp>
<String name="approvalId"></String>
<ReportSection name="attributes" category="attributes">
<ReportSection name="SHA-1" category="modified">
<String name="expected">de375d8a456a7345323babee88975ca567a2d5c4</String>
<String name="observed">3c5520382f91cb1cd898fee2da4eba3fa338d982</String>
</ReportSection>
<ReportSection name="Size" category="modified">
<String name="expected">829</String>
<String name="observed">854</String>
</ReportSection>
</ReportSection>
</ReportSection>
</ReportSection>
</ReportSection>
</ReportSection>
<ReportSection name="reportTotals" category="reportTotals">
<Integer name="summary.nodeCount">1</Integer>
<Integer name="summary.ruleCount">1</Integer>
<Integer name="summary.elementCount">2</Integer>
</ReportSection>
</ReportBody>
</ReportOutput>Hi Ritehere,
I know this is simple but am beginner in Powershell Script so I was looking for logic to go through however the output you provided is not what i am looking for and your script is too complicated, as under timestamp i wanted display value and correspoding
to display value the OID name and then name value correspoding to that OID. May be u got it wrong.
Thanks anyways. -
Trying to deploy a batch or powershell script unsuccessful
I've deployed a .cmd file out that contains a WMI script to uninstall all instances of an application called "VirtViewer". The script looks like this:
taskkill /F /IM remote-viewer.exe /T
wmic product where "name like 'VirtViewer%%'" call uninstall /nointeractive
exit /B %EXIT_CODE%
Previously, I had used MSI product codes for the uninstall, and got the same result. My original problem, is that there are currently 9 different versions of this app out there, so i am ripping them all out and replacing with 1 version. Installing over an
old version does not overwrite the older one, it instead installs a new instance.
Reading through the execmgr.log on the client, everything looks as it should.
The end result, is that nothing happens. I had originally set the program to run as hidden, but then changed it to normal but still do not see it run. The application is right where i left it, untouched. If i run the script locally it works fine, but not
when deployed. Am i missing something??
<![LOG[Service startup.]LOG]!><time="16:09:31.647+300" date="01-12-2015" component="execmgr" context="" type="1" thread="248" file="execmgr.cpp:135">
<![LOG[A user has logged on.]LOG]!><time="16:09:43.507+300" date="01-12-2015" component="execmgr" context="" type="1" thread="4256" file="execreqmgr.cpp:4911">
<![LOG[Requesting content from CAS for package VNT00018 version 21]LOG]!><time="16:11:13.649+300" date="01-12-2015" component="execmgr" context="" type="1" thread="124" file="contentaccesshelper.cpp:246">
<![LOG[Policy arrived for parent package VNT00018 program Uninstall Script]LOG]!><time="16:11:13.649+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2528" file="execreqmgr.cpp:6893">
<![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 6l, value NULL, user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:13.665+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2528" file="event.cpp:405">
<![LOG[Successfully created a content request handle {B2BA42EE-5988-47F4-BF44-ADAAC975994B} for the package VNT00018 version 21]LOG]!><time="16:11:13.665+300" date="01-12-2015" component="execmgr" context="" type="1" thread="124" file="contentaccesshelper.cpp:331">
<![LOG[Program Uninstall Script change to state STATE_ADVANCED_DOWNLOAD content available]LOG]!><time="16:11:13.665+300" date="01-12-2015" component="execmgr" context="" type="2" thread="124" file="executionrequest.cpp:3663">
<![LOG[Execution Request for advert VNT20014 package VNT00018 program Uninstall Script state change from NotExist to AdvancedDownload]LOG]!><time="16:11:13.665+300" date="01-12-2015" component="execmgr" context="" type="1" thread="124" file="executionrequest.cpp:501">
<![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 1l, value , user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:13.665+300" date="01-12-2015" component="execmgr" context="" type="1" thread="124" file="event.cpp:405">
<![LOG[Raising event:
[SMS_CodePage(437), SMS_LocaleID(1033)]
instance of SoftDistProgramOfferReceivedEvent
AdvertisementId = "VNT20014";
ClientID = "GUID:E306FF26-C884-4E36-9C03-C19523A17F40";
DateTime = "20150112211113.665000+000";
MachineName = "VM-WIN7-MIKE";
ProcessID = 1788;
SiteCode = "VNT";
ThreadID = 2528;
]LOG]!><time="16:11:13.665+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2528" file="event.cpp:715">
<![LOG[Mandatory execution requested for program Uninstall Script and advertisement VNT20014]LOG]!><time="16:11:13.680+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="execreqmgr.cpp:3527">
<![LOG[Creating mandatory request for advert VNT20014, program Uninstall Script, package VNT00018]LOG]!><time="16:11:13.680+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="execreqmgr.cpp:3653">
<![LOG[An existing MTC token was not supplied, using ExecutionRequest's Id as MTC token and this execution request is the owner of resultant MTC task.]LOG]!><time="16:11:13.696+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="executionrequest.cpp:8942">
<![LOG[Request a MTC task for execution request of package VNT00018, program Uninstall Script with request id: {D52026A7-5735-402B-868C-EF9791656512}]LOG]!><time="16:11:13.696+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="executionrequest.cpp:8966">
<![LOG[Execution Request for advert VNT20014 package VNT00018 program Uninstall Script state change from WaitingDependency to Ready]LOG]!><time="16:11:13.712+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="executionrequest.cpp:501">
<![LOG[MTC task with id {D52026A7-5735-402B-868C-EF9791656512}, changed state from 0 to 4]LOG]!><time="16:11:13.712+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="execreqmgr.cpp:6288">
<![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 1l, value , user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:13.712+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="event.cpp:405">
<![LOG[MTC signaled SWD execution request with program id: Uninstall Script, package id: VNT00018 for execution.]LOG]!><time="16:11:13.743+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="execreqmgr.cpp:6406">
<![LOG[Sending ack to MTC for task with id: {D52026A7-5735-402B-868C-EF9791656512}]LOG]!><time="16:11:13.743+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executionrequest.cpp:9005">
<![LOG[Executing program VirtViewerUninstall.cmd in Admin context]LOG]!><time="16:11:13.743+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executionrequest.cpp:3239">
<![LOG[Execution Request for advert VNT20014 package VNT00018 program Uninstall Script state change from Ready to NotifyExecution]LOG]!><time="16:11:13.743+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executionrequest.cpp:501">
<![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 1l, value , user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:13.759+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="event.cpp:405">
<![LOG[Checking content location C:\Windows\ccmcache\1c for use]LOG]!><time="16:11:13.774+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executioncontext.cpp:1663">
<![LOG[Successfully selected content location C:\Windows\ccmcache\1c]LOG]!><time="16:11:13.774+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executioncontext.cpp:1719">
<![LOG[Executing program as a script]LOG]!><time="16:11:13.774+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executionengine.cpp:82">
<![LOG[Successfully prepared command line "C:\Windows\ccmcache\1c\VirtViewerUninstall.cmd"]LOG]!><time="16:11:13.774+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="scriptexecution.cpp:650">
<![LOG[Command line = "C:\Windows\ccmcache\1c\VirtViewerUninstall.cmd", Working Directory = C:\Windows\ccmcache\1c\]LOG]!><time="16:11:13.774+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="scriptexecution.cpp:352">
<![LOG[Running "C:\Windows\ccmcache\1c\VirtViewerUninstall.cmd" with 32bitLauncher]LOG]!><time="16:11:13.774+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="scriptexecution.cpp:370">
<![LOG[Created Process for the passed command line]LOG]!><time="16:11:13.852+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="scriptexecution.cpp:513">
<![LOG[Raising event:
[SMS_CodePage(437), SMS_LocaleID(1033)]
instance of SoftDistProgramStartedEvent
AdvertisementId = "VNT20014";
ClientID = "GUID:E306FF26-C884-4E36-9C03-C19523A17F40";
CommandLine = "\"C:\\Windows\\ccmcache\\1c\\VirtViewerUninstall.cmd\"";
DateTime = "20150112211113.852000+000";
MachineName = "VM-WIN7-MIKE";
PackageName = "VNT00018";
ProcessID = 1788;
ProgramName = "Uninstall Script";
SiteCode = "VNT";
ThreadID = 2164;
UserContext = "NT AUTHORITY\\SYSTEM";
WorkingDirectory = "C:\\Windows\\ccmcache\\1c\\";
]LOG]!><time="16:11:13.852+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="event.cpp:715">
<![LOG[Raised Program Started Event for Ad:VNT20014, Package:VNT00018, Program: Uninstall Script]LOG]!><time="16:11:13.852+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="executioncontext.cpp:459">
<![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 1l, value NULL, user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:13.852+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="event.cpp:405">
<![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 1l, value , user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:13.868+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="event.cpp:405">
<![LOG[MTC task with id {D52026A7-5735-402B-868C-EF9791656512}, changed state from 4 to 5]LOG]!><time="16:11:13.884+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2164" file="execreqmgr.cpp:6288">
<![LOG[Program exit code 0]LOG]!><time="16:11:17.571+300" date="01-12-2015" component="execmgr" context="" type="1" thread="4128" file="scriptexecution.cpp:676">
<![LOG[Looking for MIF file to get program status]LOG]!><time="16:11:17.571+300" date="01-12-2015" component="execmgr" context="" type="1" thread="4128" file="executionstatus.cpp:282">
<![LOG[Script for Package:VNT00018, Program: Uninstall Script succeeded with exit code 0]LOG]!><time="16:11:17.571+300" date="01-12-2015" component="execmgr" context="" type="1" thread="4128" file="executionstatus.cpp:262">
<![LOG[Raising event:
[SMS_CodePage(437), SMS_LocaleID(1033)]
instance of SoftDistProgramCompletedSuccessfullyEvent
AdvertisementId = "VNT20014";
ClientID = "GUID:E306FF26-C884-4E36-9C03-C19523A17F40";
DateTime = "20150112211117.571000+000";
MachineName = "VM-WIN7-MIKE";
PackageName = "VNT00018";
ProcessID = 1788;
ProgramName = "Uninstall Script";
SiteCode = "VNT";
ThreadID = 4128;
UserContext = "NT AUTHORITY\\SYSTEM";
]LOG]!><time="16:11:17.587+300" date="01-12-2015" component="execmgr" context="" type="1" thread="4128" file="event.cpp:715">
<![LOG[Raised Program Success Event for Ad:VNT20014, Package:VNT00018, Program: Uninstall Script]LOG]!><time="16:11:17.587+300" date="01-12-2015" component="execmgr" context="" type="1" thread="4128" file="executioncontext.cpp:483">
<![LOG[Execution is complete for program Uninstall Script. The exit code is 0, the execution status is Success]LOG]!><time="16:11:17.587+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="execreqmgr.cpp:4165">
<![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 10l, value Result:TRUE ,SDKCallerId:, user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:17.602+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="event.cpp:405">
<![LOG[Requesting MTC to delete task with id: {D52026A7-5735-402B-868C-EF9791656512}]LOG]!><time="16:11:17.618+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="executionrequest.cpp:9036">
<![LOG[MTC task with id: {D52026A7-5735-402B-868C-EF9791656512} deleted successfully.]LOG]!><time="16:11:17.618+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="executionrequest.cpp:9065">
<![LOG[Raising client SDK event for class CCM_Program, instance CCM_Program.PackageID="VNT00018",ProgramID="Uninstall Script", actionType 1l, value , user NULL, session 4294967295l, level 0l, verbosity 30l]LOG]!><time="16:11:17.618+300" date="01-12-2015" component="execmgr" context="" type="1" thread="2564" file="event.cpp:405">I just tried using powershell to accomplish the same task, and got the same result. Script ran fine, but nothing resulted. 0 errors in the execmgr.log on the client.
Program options:
Command Line: Powershell.exe -executionpolicy Bypass -file .\VirtUninstall.ps1
the powershell script looks like this:
$app = Get-WmiObject -Class Win32_Product | Where-Object {$_.Name -match "VirtViewer*"}
$app.Uninstall()
exit /B
Again, the script runs great when launched locally, but not wehen deployed -
How to Read the "text file and csv file" through powershell Scripts
Hi All
i need to add a multiple users in a particular Group through powershell Script how to read the text and CSV files in powershell
am completly new to Powershell scripts any one pls respond ASAP.with step by step process pls
Regards:
Rajeshreddy.kHi Rajeshreddy.k,
To add multiple users to one group, I wouldn't use a .csv file since the only value you need from a list is the users to be added.
To start create a list of users that should be added to the group, import this list in a variable called $users, the group distinguishedName in a variable called $Group and simply call the ActiveDirectory cmdlet Add-GroupMember.
$Users = Get-Content -Path 'C:\ListOfUsernames.txt'
$Group = 'CN=MyGroup,OU=MyOrg,DC=domain,DC=lcl'
Add-ADGroupMember -Identity $Group -Members $Users -
Trouble adding leading zeros to numbers in PowerShell script
I am new to PowerShell scripting (so have mercy on me please!), and I'm trying to write a script that takes simplified, menu-based user input to create a folder on the network named based on a month number and the year. The month must be expressed as a two-digit
number, but I'm trying to make it simple enough that the user only needs to input a one-digit number (for the first nine months of the year) and have the script add the leading zero (for example, if a user inputs the number "2" for February, the
script will output "02").
Here is a portion of my script:
# Get current year
$year = Get-Date -Format yyyy
# Provide menu of months for user to choose from
Write-Host "Choose the name of the month for the folder you want to create."
Write-Host "1. January"
Write-Host "2. February"
Write-Host "3. March"
Write-Host "4. April"
Write-Host "5. May"
Write-Host "6. June"
Write-Host "7. July"
Write-Host "8. August"
Write-Host "9. September"
Write-Host "10. October"
Write-Host "11. November"
Write-Host "12. December"
Write-Host " "
Do {
$mNum = Read-Host "Select the number of the month (1 - 12): "
# Convert the menu item to the month name
switch ($mNum)
1 {$month = "January"}
2 {$month = "February"}
3 {$month = "March"}
4 {$month = "April"}
5 {$month = "May"}
6 {$month = "June"}
7 {$month = "July"}
8 {$month = "August"}
9 {$month = "September"}
10 {$month = "October"}
11 {$month = "November"}
12 {$month = "December"}
default {"Invalid entry. Please select a number from 1 - 12 (without the trailing period)."}
# Validate user input. Current code is cumbersome; try to find more elegant method.
While ($mNum -ne 1 -and $mNum -ne 2 -and $mNum -ne 3 -and $mNum -ne 4 -and $mNum -ne 5 -and `
$mNum -ne 6 -and $mNum -ne 7 -and $mNum -ne 8 -and $mNum -ne 9 -and $mNum -ne 10 -and `
$mNum -ne 11 -and $mNum -ne 12)
# Add leading zeros to month number
$fNum = "{0:D2}" -f $mNum
Write-Host $fNum
When I run it, I don't get the leading zero. However, when I create a very basic script, it seems to work:
$mNum = 3
$fNum = "{0:D2}" -f $mNum
Write-Host $fNum
Can anyone offer any suggestions as to what I might be doing wrong?
Also, if anyone has a suggestion on how to better validate the user input (making sure they enter a number between 1 and 12), I would appreciate that as well..NET formatting is a complicated subject
http://msdn.microsoft.com/en-us/library/26etazsy(v=vs.110).aspx#FormatStrings
I'm not sure how all that documentation applies when you attempt to format a value that is already a string.
In general, formatting is described as "Formatting is the process of converting an instance of a class,
structure, or enumeration value to its string representation". If it is already a string I'm not sure what to expect.
For example,
<# C: #> '3',3,'03',03,'003',003 | % { "{0:D2}" -f $_ }
3
03
03
03
003
03
<# C: #> -
Help modifying a powershell script
Hello,
I have recently been given a task to write/find a script that is capable of performing Full and Incremental backups. I found a script that does exactly what I need, however, it requires user input. I need this to be a scheduled task and therefore I need
the input to be a static path. Here is the script I am talking about:
#region Params
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$HashPath,
[Parameter(Position=3, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateSet("Full","Incremental","Differential")]
[System.String]
$BackupType="Full",
[Parameter(Position=4, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$LogFile=".\Backup-Files.log",
[Parameter(Position=5, Mandatory=$false,ValueFromPipeline=$false)]
[System.Management.Automation.SwitchParameter]
$SwitchToFull
#endregion
begin{
function Write-Log
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Message,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$LogFile
#endregion
try{
Write-Host $Message
Out-File -InputObject $Message -Append $LogFile
catch {throw $_}
function Get-Hash
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$HashTarget,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateSet("File","String")]
[System.String]
$HashType
#endregion
begin{
try{ $objGetHashMD5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider }
catch {throw $_ }
process{
try {
#Checking hash target is file or just string
switch($HashType){
"String" {
$objGetHashUtf8 = New-Object -TypeName System.Text.UTF8Encoding
$arrayGetHashHash = $objGetHashMD5.ComputeHash($objGetHashUtf8.GetBytes($HashTarget.ToUpper()))
break
"File" {
$arrayGetHashHash = $objGetHashMD5.ComputeHash([System.IO.File]::ReadAllBytes($HashTarget))
break
#Return hash
Write-Output $([System.Convert]::ToBase64String($arrayGetHashHash))
catch { throw $_ }
function Copy-File
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Any'})]
[System.String]
$SourceFile,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestFile
#endregion
try{
#The script fails when folder being copied to file. So the item will be removed to avoid the error.
if(Test-Path -LiteralPath $DestFile -PathType Any){
Remove-Item -LiteralPath $DestFile -Force -Recurse
#Creating destination if doesn't exist. It's required because Copy-Item doesn't create destination folder
if(Test-Path -LiteralPath $SourceFile -PathType Leaf){
New-Item -ItemType "File" -Path $DestFile -Force
#Copying file to destination directory
Copy-Item -LiteralPath $SourceFile -Destination $DestFile -Force
catch{ throw $_ }
function Backup-Files
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNull()]
[System.Collections.Hashtable]
$HashTable
#endregion
try{
$xmlBackupFilesHashFile = $HashTable
Write-Host "Backup started"
Get-ChildItem -Recurse -Path $SourceDir|ForEach-Object{
$currentBackupFilesItem = $_
#Full path to source and destination item
$strBackupFilesSourceFullPath = $currentBackupFilesItem.FullName
$strBackupFilesDestFullPath = $currentBackupFilesItem.FullName.Replace($SourceDir,$DestDir)
#Checking that the current item is file and not directory. True - the item is file.
$bBackupFilesFile = $($($currentBackupFilesItem.Attributes -band [System.IO.FileAttributes]::Directory) -ne [System.IO.FileAttributes]::Directory)
Write-Host -NoNewline ">>>Processing item $strBackupFilesSourceFullPath..."
#Generating path hash
$hashBackupFilesPath = $(Get-Hash -HashTarget $strBackupFilesSourceFullPath -HashType "String")
$hashBackupFilesFile = "d"
#If the item is file then generate hash for file content
if($bBackupFilesFile){
$hashBackupFilesFile = $(Get-Hash -HashTarget $strBackupFilesSourceFullPath -HashType "File")
#Checking that the file has been copied
if($xmlBackupFilesHashFile[$hashBackupFilesPath] -ne $hashBackupFilesFile){
Write-Host -NoNewline $("hash changed=>$hashBackupFilesFile...")
Copy-File -SourceFile $strBackupFilesSourceFullPath $strBackupFilesDestFullPath|Out-Null
#Returning result
Write-Output @{$hashBackupFilesPath=$hashBackupFilesFile}
else{
Write-Host -NoNewline "not changed..."
Write-Host "done"
Write-Host "Backup completed"
catch { throw $_ }
function Backup-Full
[CmdletBinding()]
[OutputType([System.String])]
#region Params
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$HashFile,
[Parameter(Position=3, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$ChainKey
#endregion
try{
#Creating an empty hash table
$xmlBackupFullHashFile = @{}
#Starting directory lookup
$uintBackupFullCount = 0
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$ChainKey\Full_" + $(Get-Date -Format "ddMMyyyy")) -HashTable $xmlBackupFullHashFile|`
ForEach-Object{
$xmlBackupFullHashFile.Add([string]$_.Keys,[string]$_.Values)
$uintBackupFullCount++
#Saving chain key.
$xmlBackupFullHashFile.Add("ChainKey",$ChainKey)
Write-Host -NoNewline "Saving XML file to $HashFile..."
Export-Clixml -Path $HashFile -InputObject $xmlBackupFullHashFile -Force
Write-Host "done"
Write-Output $uintBackupFullCount
catch { throw $_ }
function Backup-Diff
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'leaf'})]
[System.String]
$HashFile
#endregion
try{
#Loading hash table
$xmlBackupDiffHashFile = Import-Clixml $HashFile
$chainKeyBackupDiffDifferential = $xmlBackupDiffHashFile["ChainKey"]
$uintBackupDiffCount = 0
#Starting directory lookup
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$chainKeyBackupDiffDifferential\Differential_" + $(Get-Date -Format "ddMMyyyy.HHmm")) -HashTable $xmlBackupDiffHashFile|`
ForEach-Object{ $uintBackupDiffCount++ }
Write-Output $uintBackupDiffCount
catch { throw $_ }
function Backup-Inc
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'leaf'})]
[System.String]
$HashFile
#endregion
try{
#Loading hash table
$xmlBackupIncHashFile = Import-Clixml $HashFile
$chainKeyBackupIncIncremental = $xmlBackupIncHashFile["ChainKey"]
$uintBackupIncCount = 0
#Starting directory lookup
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$chainKeyBackupIncIncremental\Incremental_" + $(Get-Date -Format "ddMMyyyy.HHmm")) -HashTable $xmlBackupIncHashFile|`
ForEach-Object{
$xmlBackupIncHashFile[[string]$_.Keys]=[string]$_.Values
$uintBackupIncCount++
Write-Host -NoNewline "Saving XML file to $HashFile..."
Export-Clixml -Path $HashFile -InputObject $xmlBackupIncHashFile -Force
Write-Host "Done"
Write-Output $uintBackupIncCount
catch { throw $_ }
#0 - is OK. 1 - some error
$exitValue=0
process{
try{
$filesCopied=0
$strSourceFolderName = $(Get-Item $SourceDir).Name
$strHasFile = $("$HashPath\Hash_$strSourceFolderName.xml")
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir started")
#Automatically switch to full backup
$bSwitch = $(!$(Test-Path -LiteralPath $strHasFile -PathType "Leaf") -and $SwitchToFull)
Write-Log -Message $strMessage -LogFile $LogFile
switch($true){
$($BackupType -eq "Full" -or $bSwitch) {
$filesCopied = Backup-Full -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile -ChainKey $("Backup_$strSourceFolderName" + "_" + $(Get-Date -Format "ddMMyyyy"))
break
$($BackupType -eq "Incremental") {
$filesCopied = Backup-Inc -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile
break
$($BackupType -eq "Differential") {
$filesCopied = Backup-Diff -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile
break
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir completed successfully. $filesCopied items were copied.")
Write-Log -Message $strMessage -LogFile $LogFile
Write-Output $filesCopied
catch {
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir failed:" + $_)
Write-Log -Message $strMessage -LogFile $LogFile
$exitValue = 1
end{exit $exitValue}
I have some experience writing Powershell scripts,but I am lost at how this script prompts for Source and Destination paths. I tried modifying the Param section, but this didnt work and up until now I thought the only way you could get a prompt was with
"read-host". Any and all education on this matter would be greatly appreciated. (Side note: I have posted this question on the forum in which I found it and have not got an answer yet).
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$HashPath,
[Parameter(Position=3, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateSet("Full","Incremental","Differential")]
[System.String]
$BackupType="Full",
[Parameter(Position=4, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$LogFile=".\Backup-Files.log",
[Parameter(Position=5, Mandatory=$false,ValueFromPipeline=$false)]
[System.Management.Automation.SwitchParameter]
$SwitchToFull
#endregion
begin{
function Write-Log
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Message,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$LogFile
#endregion
try{
Write-Host $Message
Out-File -InputObject $Message -Append $LogFile
catch {throw $_}
function Get-Hash
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$HashTarget,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateSet("File","String")]
[System.String]
$HashType
#endregion
begin{
try{ $objGetHashMD5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider }
catch {throw $_ }
process{
try {
#Checking hash target is file or just string
switch($HashType){
"String" {
$objGetHashUtf8 = New-Object -TypeName System.Text.UTF8Encoding
$arrayGetHashHash = $objGetHashMD5.ComputeHash($objGetHashUtf8.GetBytes($HashTarget.ToUpper()))
break
"File" {
$arrayGetHashHash = $objGetHashMD5.ComputeHash([System.IO.File]::ReadAllBytes($HashTarget))
break
#Return hash
Write-Output $([System.Convert]::ToBase64String($arrayGetHashHash))
catch { throw $_ }
function Copy-File
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Any'})]
[System.String]
$SourceFile,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestFile
#endregion
try{
#The script fails when folder being copied to file. So the item will be removed to avoid the error.
if(Test-Path -LiteralPath $DestFile -PathType Any){
Remove-Item -LiteralPath $DestFile -Force -Recurse
#Creating destination if doesn't exist. It's required because Copy-Item doesn't create destination folder
if(Test-Path -LiteralPath $SourceFile -PathType Leaf){
New-Item -ItemType "File" -Path $DestFile -Force
#Copying file to destination directory
Copy-Item -LiteralPath $SourceFile -Destination $DestFile -Force
catch{ throw $_ }
function Backup-Files
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNull()]
[System.Collections.Hashtable]
$HashTable
#endregion
try{
$xmlBackupFilesHashFile = $HashTable
Write-Host "Backup started"
Get-ChildItem -Recurse -Path $SourceDir|ForEach-Object{
$currentBackupFilesItem = $_
#Full path to source and destination item
$strBackupFilesSourceFullPath = $currentBackupFilesItem.FullName
$strBackupFilesDestFullPath = $currentBackupFilesItem.FullName.Replace($SourceDir,$DestDir)
#Checking that the current item is file and not directory. True - the item is file.
$bBackupFilesFile = $($($currentBackupFilesItem.Attributes -band [System.IO.FileAttributes]::Directory) -ne [System.IO.FileAttributes]::Directory)
Write-Host -NoNewline ">>>Processing item $strBackupFilesSourceFullPath..."
#Generating path hash
$hashBackupFilesPath = $(Get-Hash -HashTarget $strBackupFilesSourceFullPath -HashType "String")
$hashBackupFilesFile = "d"
#If the item is file then generate hash for file content
if($bBackupFilesFile){
$hashBackupFilesFile = $(Get-Hash -HashTarget $strBackupFilesSourceFullPath -HashType "File")
#Checking that the file has been copied
if($xmlBackupFilesHashFile[$hashBackupFilesPath] -ne $hashBackupFilesFile){
Write-Host -NoNewline $("hash changed=>$hashBackupFilesFile...")
Copy-File -SourceFile $strBackupFilesSourceFullPath $strBackupFilesDestFullPath|Out-Null
#Returning result
Write-Output @{$hashBackupFilesPath=$hashBackupFilesFile}
else{
Write-Host -NoNewline "not changed..."
Write-Host "done"
Write-Host "Backup completed"
catch { throw $_ }
function Backup-Full
[CmdletBinding()]
[OutputType([System.String])]
#region Params
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$HashFile,
[Parameter(Position=3, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$ChainKey
#endregion
try{
#Creating an empty hash table
$xmlBackupFullHashFile = @{}
#Starting directory lookup
$uintBackupFullCount = 0
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$ChainKey\Full_" + $(Get-Date -Format "ddMMyyyy")) -HashTable $xmlBackupFullHashFile|`
ForEach-Object{
$xmlBackupFullHashFile.Add([string]$_.Keys,[string]$_.Values)
$uintBackupFullCount++
#Saving chain key.
$xmlBackupFullHashFile.Add("ChainKey",$ChainKey)
Write-Host -NoNewline "Saving XML file to $HashFile..."
Export-Clixml -Path $HashFile -InputObject $xmlBackupFullHashFile -Force
Write-Host "done"
Write-Output $uintBackupFullCount
catch { throw $_ }
function Backup-Diff
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'leaf'})]
[System.String]
$HashFile
#endregion
try{
#Loading hash table
$xmlBackupDiffHashFile = Import-Clixml $HashFile
$chainKeyBackupDiffDifferential = $xmlBackupDiffHashFile["ChainKey"]
$uintBackupDiffCount = 0
#Starting directory lookup
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$chainKeyBackupDiffDifferential\Differential_" + $(Get-Date -Format "ddMMyyyy.HHmm")) -HashTable $xmlBackupDiffHashFile|`
ForEach-Object{ $uintBackupDiffCount++ }
Write-Output $uintBackupDiffCount
catch { throw $_ }
function Backup-Inc
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'leaf'})]
[System.String]
$HashFile
#endregion
try{
#Loading hash table
$xmlBackupIncHashFile = Import-Clixml $HashFile
$chainKeyBackupIncIncremental = $xmlBackupIncHashFile["ChainKey"]
$uintBackupIncCount = 0
#Starting directory lookup
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$chainKeyBackupIncIncremental\Incremental_" + $(Get-Date -Format "ddMMyyyy.HHmm")) -HashTable $xmlBackupIncHashFile|`
ForEach-Object{
$xmlBackupIncHashFile[[string]$_.Keys]=[string]$_.Values
$uintBackupIncCount++
Write-Host -NoNewline "Saving XML file to $HashFile..."
Export-Clixml -Path $HashFile -InputObject $xmlBackupIncHashFile -Force
Write-Host "Done"
Write-Output $uintBackupIncCount
catch { throw $_ }
#0 - is OK. 1 - some error
$exitValue=0
process{
try{
$filesCopied=0
$strSourceFolderName = $(Get-Item $SourceDir).Name
$strHasFile = $("$HashPath\Hash_$strSourceFolderName.xml")
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir started")
#Automatically switch to full backup
$bSwitch = $(!$(Test-Path -LiteralPath $strHasFile -PathType "Leaf") -and $SwitchToFull)
Write-Log -Message $strMessage -LogFile $LogFile
switch($true){
$($BackupType -eq "Full" -or $bSwitch) {
$filesCopied = Backup-Full -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile -ChainKey $("Backup_$strSourceFolderName" + "_" + $(Get-Date -Format "ddMMyyyy"))
break
$($BackupType -eq "Incremental") {
$filesCopied = Backup-Inc -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile
break
$($BackupType -eq "Differential") {
$filesCopied = Backup-Diff -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile
break
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir completed successfully. $filesCopied items were copied.")
Write-Log -Message $strMessage -LogFile $LogFile
Write-Output $filesCopied
catch {
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir failed:" + $_)
Write-Log -Message $strMessage -LogFile $LogFile
$exitValue = 1
end{exit $exitValue}Hi Ryan Blaeholder,
Thanks for your posting.
To schedule a powershell script with input value, instead of modifying the script above, you can also try to add the input during creating a scheduled task like this:(save the script above as D:\backup.ps1)
-command "& 'D:\backup.ps1' 'input1' 'input2'"
For more detailed information, please refer to this article to complete:
Schedule PowerShell Scripts that Require Input Values:
http://blogs.technet.com/b/heyscriptingguy/archive/2011/01/12/schedule-powershell-scripts-that-require-input-values.aspx
I hope this helps.
We
are trying to better understand customer views on social support experience, so your participation in this
interview project would be greatly appreciated if you have time.
Thanks for helping make community forums a great place. -
PowerShell script : Directory object not found error in Get-ADGroupMember
I am new in powershell scripting. I am writing a script to add users in different AD Groups. while doing so I do the following:
Check if the user already exist in the group:
$mbr_exist = Get-ADGroupMember $grpname | Where-Object {$_.SamAccountName -eq $sam}
If user does not exist then add the user to the group.
When I manually run the script its runs flawless, without any errors. But when I schedule the script to run it gives an error as follows:
3/30/2015 8:32:15 AM Directory object not foundAt + $mbr_exist = Get-ADGroupMember $grpname | Where-Object {$_.SamAc ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~ Error at Line:$mbr_exist = Get-ADGroupMember
$grpname | Where-Object {$_.SamAccountName -eq $sam}
The strange thing is the user for which it throws the error is present in the group.I am not sure why this error is occurring when scheduled. Can any one please help? All the suggestions will be appreciated
Note: (The script is scheduled using Windows Task Scheduler)
try
# # Initialize the variables we will use
$status = 'false'
$drivename = "H:"
$sysdate = Get-Date -UFormat "%m_%d_%Y"
$foldername = $drivename + "\Script_Result\PowershellData"+ $sysdate
$backup_folder = "$foldername\AD_Groups_Backup"
$updatedGroup = "$foldername\Updated_AD_Groups_LogFiles"
$LogFilePath = "$foldername\Log_Update_ADGroups"+$sysdate+".log"
# # Initialize the arrays we will use
$GroupArray = @()
# # maintain log of program startup
$logdate = get-date
$logdate.ToString() + "`tStarted script to Update AD user Groups..." | Out-File -FilePath $LogFilePath
# # Create a sub folder to store the backup files
$fileexist = Test-Path $backup_folder -PathType Container
if($fileexist -ne 'False')
New-Item -ItemType Directory $backup_folder
# # Create a sub folder to store Updated AD group Log files
$fileexist = Test-Path $updatedGroup -PathType Container
if($fileexist -ne 'False')
New-Item -ItemType Directory $updatedGroup
# # Take back up of the AD groups data
Get-ADGroupMember -Identity "Group1" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
Get-ADGroupMember -Identity "Group2" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
Get-ADGroupMember -Identity "Group3" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
Get-ADGroupMember -Identity "Group4" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
(an so on..... 11 such groups )
# # Fetch AD Users data
$ADusers = Get-ADUser -filter {(EmployeeNumber -gt 1) -and (EmployeeNumber -ne "N/A") -and (Enabled -eq $true)} -Properties * | Sort-Object -Property EmployeeNumber
$ADusers.Count
foreach($u in $ADusers)
$sam = $u.SamAccountName
$empnum = $u.EmployeeNumber
$mgr = $u.mgr
$fsal = $u.'fsalary-Hourly'
$comp = $u.Company
$ofc = $u.Office
Write-Host "$sam : $empnum : $mgr :$fsal : $comp : $ofc" -ForegroundColor Yellow
$GroupArray = @()
# # Check if the user fits in any of the 11 scenarios
if($comp -eq "US")
# scenario 7
write-host "7. Add to US Employees"
$GroupArray += "US Employees"
if($mgr -eq "Y")
Write-Host "1. ADD to US MAnagers"
$group = "US Managers"
$GroupArray += $group
if(($fsal -eq "Hourly") -and ($ofc -ne "Canton"))
Write-Host "3. Add to US Hourly (excluding Canton)"
$group = "US Hourly (excluding Canton)"
$GroupArray += $group
if(($fsal -eq "Hourly") -and ($ofc -eq "Canton"))
write-host "4. Add to US Canton Hourly"
$group = "US Canton Hourly"
$GroupArray += $group
if(($fsal -eq "Salaried") -and ($ofc -eq "Corporate" -or $ofc -eq "Landis Lakes 1" -or $ofc -eq "Landis Lakes 2"))
Write-Host "5. Add to US Salaried Corporate"
$group = "US Salaried Corporate"
$GroupArray += $group
if(($fsal -eq "Salaried") -and ($ofc -ne "Corporate" -and $ofc -ne "Landis Lakes 1" -and $ofc -ne "Landis Lakes 2"))
Write-Host "6. Add to US Salaried Plant"
$group = "US Salaried Plant"
$GroupArray +=$group
elseif($comp -eq "canada")
# scenario 9
write-host "9. Canada Employees"
$GroupArray += "Canada Employees"
if($mgr -eq "Y")
Write-Host "2. Add to Canada Managers"
$group = "Canada Managers"
$GroupArray += $group
if($fsal -eq "Hourly")
Write-Host "10. Add to Canada Hourly"
$group = "Canada Hourly"
$GroupArray += $group
if($fsal -eq "Salaried")
Write-Host "11. Add to Canada Salaried Plant"
$group = "Canada Salaried Plant"
$GroupArray += $group
elseif($ofc -eq "Corporate" -or $ofc -eq "Landis Lakes 1" -or $ofc -eq "Landis Lakes 2")
Write-Host "8. Add to Corporate Employees"
$GroupArray += "Corporate Employees"
write-host "Final Group List" -ForegroundColor Green
$grplen = $GroupArray.Length
#$GroupArray
$grplen
for($i= 0; $i -lt $grplen; $i++)
$grpname = $GroupArray[$i]
write-host "$sam will be added to Group : $grpname" -ForegroundColor Magenta
# # Check if the user is already present in the Group
$mbr_exist = Get-ADGroupMember $grpname | Where-Object {$_.SamAccountName -eq $sam}
if($mbr_exist -eq $null)
# #Add user to US Managers group
Add-ADGroupMember -Identity $grpname -Members $sam
Write-Host "1. User $sam is added to $grpname group" -ForegroundColor Green
# # documenting the user list that are added to this group
$grpmbr = New-Object PSObject
$grpmbr | Add-Member -MemberType NoteProperty -Name "EmployeeNumber" -Value $empnum
$grpmbr | Add-Member -MemberType NoteProperty -Name "SamAccountName" -Value $sam
$grpmbr | Add-Member -MemberType NoteProperty -Name "Name" -Value $u.Name
$grpmbr | Add-Member -MemberType NoteProperty -Name "DistinguishedName" -Value $u.DistinguishedName
$grpmbr | Add-Member -MemberType NoteProperty -Name "mgr" -Value $mgr
$grpmbr | Add-Member -MemberType NoteProperty -Name "Company" -Value $comp
$grpmbr | Add-Member -MemberType NoteProperty -Name "Salary/Hourly" -Value $fsal
$grpmbr | Add-Member -MemberType NoteProperty -Name "Office" -Value $ofc
$grpmbr | Add-Member -MemberType NoteProperty -Name "ADGroup" -Value $grpname
$grpmbr | Export-Csv "$updatedGroup\ADUsers_To_Group($grpname)_$sysdate.csv" -Append -NoTypeInformation
else
Write-Host "Member $sam already exist in $grpname group" -ForegroundColor Red
$logdate = get-date
$logdate.ToString() + "`tCompleted script to Update Update AD Groups..." | Out-File -FilePath $LogFilePath -Append
$status = 'true'
return $status
catch
$err_lineno = $error[0].InvocationInfo.ScriptLineNumber
$err_line = $error[0].InvocationInfo.Line
$ExceptionMessage = $_.Exception.Message
#$ExceptionMessage
$error_info = $error[0].ToString() + $error[0].InvocationInfo.PositionMessage
Write-Host "$error_info " -ForegroundColor Red
$FailedItem = $_.Exception.ItemName
if($ExceptionMessage)
$logdate.ToString() + "`t $error_info " | out-file "$foldername\ErrorLog_Update_AD_Groups$sysdate.log" -append
"Line Number: $err_lineno . `nError at Line: $err_line" | out-file "$foldername\ErrorLog_Update_AD_Groups$sysdate.log" -append
#Invoke-Item "C:\ErrorLog.log"
$status = 'false'
return $statusHi mdkelly, Sorry for such a late reply (due to credential issues).
I am using Windows task scheduler to schedule the task. I am given the administrator access to the server (Windows Server 2012). So I think I set to run the script under system account.
My apologies for asking this, am I missing something while scheduling the script through task scheduler? how to check if the scheduled task is running under who's credentials? How to pass my (admin) credentials, so that the script execution won't face
a problem? Any suggestion on the above questions will be helpful. (I tried to search on net for the questions but didn't get any conclusive answers)
Thanks in advance. -
Powershell script to update mailbox search
I am trying to update a mailbox search using a powershell script:
Stop-MailboxSearch -Identity "LitHolds" -confirm:$false
$members = (import-csv -Path "Path"| ForEach-Object{$_.SamAccountName})
foreach ($user in $members)
Set-MailboxSearch -Identity "LitHolds" -SourceMailboxes $user.samaccountname
Start-MailboxSearch -Identity "LitHolds" -confirm:$false
I essentially have our sysadmins populating a csv file and then they run this script manually every night with the latest updates. They are telling me that the mailbox search is empty.
When I run the script I am getting a watson error immediately after with the following:
WARNING: An unexpected error has occurred and a Watson dump is being generated: Value cannot be null.
Parameter name: legacyDN
Value cannot be null.
Parameter name: legacyDN
+ CategoryInfo : NotSpecified: (:) [Stop-MailboxSearch], ArgumentNullException
+ FullyQualifiedErrorId : System.ArgumentNullException,Microsoft.Exchange.Management.Tasks.StopMailboxSearch
+ PSComputerName : Exchange Server Name
What I don't understand is why it's looking for a legacyDN??
Anyone able to do something similar?
ChuckHi Chuck,
I would like to verify if you have a legacy Exchange.
The LegacyDN property indicates the legacyDN of the mailbox and matches the legacyExchangeDN attribute of the user object in Microsoft Active Directory.
If there is any update, please feel free to let me know.
Best regards,
Amy
Amy Wang
TechNet Community Support -
Calling powershell script from a batch file
Hello All,
I have a batch script that calls a powershell script. Before calling the script I set the execution policy to unrestricted, but when it gets to the line that calls the batch script i still get the confirmation in the command window: "Do you want to
perform this operation" I then have to press Y for the PS script to run and then my batch script finishes.
Does anyone know the setting I need to change in order to suppress the confirmation?
Note: this is Windows 8, see code below
set THIS_DIR=%~dp0
powershell Set-ExecutionPolicy unrestricted
powershell %THIS_DIR%MyScript.ps1 "param1"I may sound like a jerk but you really want to look at PowerShell.exe /?
PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
[-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
[-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
[-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
[-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
PowerShell[.exe] -Help | -? | /?
-PSConsoleFile
Loads the specified Windows PowerShell console file. To create a console
file, use Export-Console in Windows PowerShell.
-Version
Starts the specified version of Windows PowerShell.
Enter a version number with the parameter, such as "-version 2.0".
-NoLogo
Hides the copyright banner at startup.
-NoExit
Does not exit after running startup commands.
-Sta
Starts the shell using a single-threaded apartment.
Single-threaded apartment (STA) is the default.
-Mta
Start the shell using a multithreaded apartment.
-NoProfile
Does not load the Windows PowerShell profile.
-NonInteractive
Does not present an interactive prompt to the user.
-InputFormat
Describes the format of data sent to Windows PowerShell. Valid values are
"Text" (text strings) or "XML" (serialized CLIXML format).
-OutputFormat
Determines how output from Windows PowerShell is formatted. Valid values
are "Text" (text strings) or "XML" (serialized CLIXML format).
-WindowStyle
Sets the window style to Normal, Minimized, Maximized or Hidden.
-EncodedCommand
Accepts a base-64-encoded string version of a command. Use this parameter
to submit commands to Windows PowerShell that require complex quotation
marks or curly braces.
-File
Runs the specified script in the local scope ("dot-sourced"), so that the
functions and variables that the script creates are available in the
current session. Enter the script file path and any parameters.
File must be the last parameter in the command, because all characters
typed after the File parameter name are interpreted
as the script file path followed by the script parameters.
-ExecutionPolicy
Sets the default execution policy for the current session and saves it
in the $env:PSExecutionPolicyPreference environment variable.
This parameter does not change the Windows PowerShell execution policy
that is set in the registry.
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
If the value of Command is "-", the command text is read from standard
input.
If the value of Command is a script block, the script block must be enclosed
in braces ({}). You can specify a script block only when running PowerShell.exe
in Windows PowerShell. The results of the script block are returned to the
parent shell as deserialized XML objects, not live objects.
If the value of Command is a string, Command must be the last parameter
in the command , because any characters typed after the command are
interpreted as the command arguments.
To write a string that runs a Windows PowerShell command, use the format:
"& {<command>}"
where the quotation marks indicate a string and the invoke operator (&)
causes the command to be executed.
-Help, -?, /?
Shows this message. If you are typing a PowerShell.exe command in Windows
PowerShell, prepend the command parameters with a hyphen (-), not a forward
slash (/). You can use either a hyphen or forward slash in Cmd.exe.
Hope that helps! Jason -
Powershell Script to Enable and Disable SharePoint list versioning
Hi,
We have a Sharepoint list with a date and time field named 'Today' which we update overnight
via PowerShell script to give the current date and this recalculates other calculated fields
in the list.
All is fine but we have versioning enabled on the list and so we get a new version created everyday.
Is there a way to disable the versioning prior to running the update and then re-enable
after?
This is the script
Add-PSSnapin Microsoft.SharePoint.PowerShell
Start-SPAssignment -Global
$SPWeb = Get-SPWeb "<SharePointSiteUrl>"
$List = $SPWeb.Lists["ListName"]
$Items = $List.Items
foreach ($item in $items)
$modifiedBy = $item["Editor"]
$modified = $item["Modified"]
$item["Today"] = Get-Date
$item["Editor"] = $modifiedBy
$item["Modified"] = $modified
$item.Update()
$list.Update()
$SPWeb.Dispose()
Stop-SPAssignment -GlobalHi
Here is a quick powershell script to iterate a site collection and remove versioning on all list of base-type Document Library. Also the iteration removes all the current versions of list items. Great for freeing up space and also to make publishing sites
a little more easy to manage content for trusted content approvers!
Check the below powershell script
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
# Get site
$site = new-object Microsoft.SharePoint.SPSite("http://YoServer:1002")
# Iterate all the webs of the site
foreach ($web in $site.AllWebs)
# loop through all lists in web
foreach ($list in $web.Lists)
# Ensure list is of base Document Library
if ($list.BaseType -ne "DocumentLibrary")
# Move on
continue
# Loop through each item
foreach ($item in $list.Items)
# Get the file
$file = $item.File
# Delete all versions
$file.Versions.DeleteAll()
# Remove version from the list
$list.EnableVersioning = $false
$list.EnableModeration = $false
# We still want to ensure check out
$list.ForceCheckout = $true
$list.Update()
$web.Dispose();
$site.Dispose();
Please mark the Answer and Vote me if you think that it will help you to resolved your issue -
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-WithWMII 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 change the target destination on a shortcut file.
Hi All,
I am in a middle of a new file server implementation and have come across a problem where the items on the old file server has been archived and moved to another server and in place a shortcut is left at the original location. The current target of those
shortcut is going to be changed and thus I need to change the Target destination on those various shortcuts files. I am new to powershell and will really appreciate if someone can assist me with a powershell script for the below steps:
To find all shortcut files (Excel, word, powerpoint and other types) whose current target destination is \\abcserver\z\abcpath
Change the Target destination to \\xyzserver\z\abcpath on the shortcut file and apply the change.
Effectively only change shortcut files whose current target begins with "\\abcserver\" and change to "\\xyzserver\"
Search for the next shortcut and continue changing it.
Hope the above makes sense and appreciate the assistance.
Thanks!Did you look?
https://www.google.com/?gws_rd=ssl#newwindow=1&q=powershell+change+shortcut+path
¯\_(ツ)_/¯ -
Hello, we have a two state monitor and I would like to channel the Alert Context to Alert Description.
The powershell script being used to find the stopped services is pasted below:
$API = new-object -comObject "MOM.ScriptAPI"
$bag = $api.CreatePropertyBag()
$ServiceStatus = Get-WmiObject -class win32_service |where {$_.startmode -eq'Auto'-and $_.State -eq 'Stopped' -and
$_.name -ne 'wuauserv'}
if (!$ServiceStatus) #if there are no automatic services that are stopped, we are healthy.
write-host "good"
$bag.addvalue("State","good")
if ($servicestatus) #if there are any automatic services that are stopped, we are unhealthy.
write-host "bad"
$bag.addvalue("State","bad")
foreach ($service in $servicestatus) #enumerate the stopped services
$bag.addValue("$($Service.Name):","$($Service.state)")
$bag
$API.Return($BAG)
The results of the services that are stopped are being captured in the Alert Context”. How can I pipe the Alert Context to “Alert Description” to obtain a meaningful alert?
Alert Context data:
Property Name Property Value
State
bad
clr_optimization_v4.0.30319_32: Stopped
clr_optimization_v4.0.30319_64: Stopped
How can I pipe to Alert Description in SCOM 2012?
Thanks,
Kapil Dham
Kapil Dhamyou don't need write-host
you should create
$bag.addvalue("ServiceName1","StateOK")
$bag.addvalue("ServiceName2","StateStopped")
and in alert description you will see
ServiceName1
StateOK
ServiceName2
StateStopped
So try $bag.addValue($Service.Name,$Service.state)
and $Data/Context/Property$ -
System.Drawing.Bitmap in a scheduled powershell script
I've written a powershell script to date stamp multipage tiffs, but I check to make sure the file name follows the correct format before doing so. The file name must contain the date, sequence number, and number of pages. The script works fine when run manually,
but when run from task scheduler it fails to query the number of pages in the TIFF. Any ideas why the .NET features wouldn't work from a powershell script run as a scheduled task?
I am putting the page number in the variable "count" by doing the following:
$i=[System.Drawing.Bitmap]::FromFile($file.Fullname);$i.GetFrameCount($i.FrameDimensionsList[0])
$count=$i.GetFrameCount([System.Drawing.Imaging.FrameDimension]::Page)
FULL SCRIPT FOLLOWS
#Define the input and output folders and date format
$Original_TIFFs="C:\scans"
$Modified_TIFFs=";\\test\Shared\SDS\"
$date = get-date -Format d
$datename=Get-Date -format yyyyMMdd
Set-Location $Original_TIFFs
#Configure email settings
$emailFrom = "removed"
$emailTo = "removed"
$smtpServer = "removed"
$body = "Rename scanned claims file to the correct format. This email was sent from: ", $env:computername
#Define the location of the TIFF command line executable and its parameters
$200DLL='C:\TiffDLL200Commandline\Cmd200.exe '
$arg1='"FILE='
#Modify arg2 to put the output directory in front of the ; if don't want to overwrite current file
#$arg2=';|OW=Yes|BITS=2|TEXT=2;Received Date: '
$arg2=$modified_TIFFs
$arg3=';|BITS=2|TEXT=2;Received Date: '
$arg4='|TEXTOPS=-5;;10;14;"'
$files=Get-ChildItem $Original_TIFFs -Filter *.tif
if ($files -eq $null)
$subject = "No files to process today, directory empty."
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$body = "No files were processed today. This email was sent from: ", $env:computername
$smtp.Send($emailFrom, $emailTo, $subject, $body)
else
foreach ($file in $files)
#Begin loop to check each file and process
#Loads subsystems for opening TIFFs and second line puts the number of images into variable
$i=[System.Drawing.Bitmap]::FromFile($file.Fullname);$i.GetFrameCount($i.FrameDimensionsList[0])
$count=$i.GetFrameCount([System.Drawing.Imaging.FrameDimension]::Page)
#If statement checks if filename format is correct
if ($file -match '^\d{8}\d{3}_H_S_\d+_\d{8}[.tif]{4}$')
$file.name -match '^(?<date1>\d{8})\d{3}_H_S_(?<page_count>\d+)_(?<date2>\d{8})[.tif]{4}$' #Regex to put tests in $matches to check against
if (($matches.date1 -eq $datename) -and ($matches.date2 -eq $datename)) #Check if filename contains correct date
if ($count -eq $matches.page_count) #Check if filename
contains the correct page count
#insert TIFF modification
$allargs=$200Dll+$arg1+$file+$arg2+$file+$arg3+$date+$arg4
cmd /c $allargs
#cmd /c xcopy $file \\test\shared\SDS #Deprecated because now having
TIFF200DLL create a new file rather than overwrite
$i.Dispose()
#Close file stream so file can be deleted: http://support.microsoft.com/kb/814675
Remove-Item $file.Name
#Next section is for a different output directory; Setup a seperate batch file to delete original TIFFs in the middle of the night
<#
$allargs="cmd200 "+$arg1+$file+";"+$Modified_TIFFs+";"+$arg2+$date+$arg3
cmd /c $allargs
#>
else
#else statement to send out error message if the number of pages differs from name
$subject = "The number of pages in the file ", $file.FullName, "differs from the actual count of ", $count, ". File will not be sent, please correct before tomorrow for processing."
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
} #Close IF/THEN for correct date is in filename
else
$subject = "Date portion of filename is incorrect, please fix. File will not be sent to SDS", $file.FullName," ."
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
} #Close IF/THEN for initial filename check
else
$subject = "File does not meet proper naming convention and will not be stamped nor sent to SDS", $file.FullName, " ."
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
} #Close FOR loop
} #Close Else for check if FILES=NULLYou are buikding thisin the ISE?
You need too add:
add-type -AssemblyName System.Drawing
¯\_(ツ)_/¯
Maybe you are looking for
-
Ipod Nano 3rd gen 4gb unresponsive
So I have never had an issue with my ipod till this weekend. I plugged it in to my computer to sync and charge, the ipod had about 25% charge left on it. From there things started getting weird. My computer wouldn't recognize the ipod, so I reset it
-
I am an Oracle developer running oracle 9i Db and oracle 9iAs using Jinititor on my browser. I am trying to get a form to run Local Host commands. I have downloaded host.jar from Oracle and have certified and checked that is certified using the Java
-
Is there any way of setting the directory the file chooser opens, as a default? If the files you are supposed to choose between are in the program's folder, I want the file chooser to open there, not somewhere else, so the user has to look around for
-
Please Help! Process: iBooks [794] Path: /Applications/iBooks.app/Contents/MacOS/iBooks Identifier: com.apple.iBooksX Version: 1.0.1 (281) Build Info: iBooks-281000000000000~1 Code Type: X86-64 (Native) Pare
-
Determine when a signal changes state and then evaluate second channel
Ok, I need some help from you math geniuses (or those that remember calculus). I am recording two signals to a TDMS file, one is a pressure measurement and the other is a trigger monitor channel (basically it records a voltage change when the device