Powershell script to check IP of Website
Yes, true enough. I was thinking more along the lines of a simple check to see if the site went "down" but had actually changed IP.
Personally, I would recommend using a graphical monitor likePRTG. The free version allows for up to 100sensors. You canuse the DNS sensor to monitor for IP address changes of the DNS address and if it doesn't match it can alert.
But here's a PowerShell Script (replace the values of the variables at the beginning of the script):Powershell$WebsiteAddress = "resolver1.opendns.com"$IPAddress = "208.67.222.222"$ToEmailAddress = "[email protected]"$FromEmailAddress = "[email protected]"$MailServer = "mail.domain.com"Clear-DNSClientCache$ResolvedWebsite = Resolve-DNSName $WebsiteAddressIf ($ResolvedWebsite.IPAddress -ne $IPAddress) {Send-MailMessage -To $ToEmailAddress -From $FromEmailAddress -SmtpServer $MailServer -Subject "Notification: $WebsiteAddress IP Address Change" -Body "The IP address for $WebsiteAddress has changed to $(...
Similar Messages
-
Hi,
I have a text file in which some SamAccountNames are present.I need to check the file while creating a new users through ADUC console.If a username that is going to create through ADUC console is present in the file, then it should prompt a message
that the user is already present in the text file.
Is there any possibility of contacting the powershell script from the ADUC console.If so, then while creating a new user through ADUC console, what is the proceedure for executing that powershell script.
please provide me the approriate solutions.
Thanks
Prasanthi kRun the below Powershell Script for users are exist or not in AD. Later you can create the users.
#Find Users exist in AD or Not?
#Biswajit Biswas
$users = get-content c:\users.txt
foreach ($user in $users) {
$User = Get-ADUser -Filter {(samaccountname -eq $user)}
If ($user -eq $Null) {"User does not exist in AD ($user)" }
Else {"User found in AD ($user)"}
Active Directory Users attributes-Powershell
http://gallery.technet.microsoft.com/scriptcenter/Getting-Users-ALL-7417b71d
Regards~Biswajit
Disclaimer: This posting is provided & with no warranties or guarantees and confers no rights.
MCP 2003,MCSA 2003, MCSA:M 2003, CCNA, MCTS, Enterprise Admin
MY BLOG
Domain Controllers inventory-Quest Powershell
Generate Report for Bulk Servers-LastBootUpTime,SerialNumber,InstallDate
Generate a Report for installed Hotfix for Bulk Servers -
Hi there,
On my SharePoint site - some places (Sites/Lists etc) have given permissions to "NT Authority\All Authenticated Users"
We need to remove these permissions and instead give permissions to "Forest1\Domain Users" and "Forest1\Domain Users"
PowerSHell script to do above will be appreciated.
Thank you so much.Hello,
In order to check whether "NT Authority\All Authenticated Users" are present in your site use this reference - Link
Remove permission script reference - Link
Finally grant permission script reference - link
Kindly mark it as answer if it helps you.
-Hatim -
Hi Guys,
I was hoping someone could help me with a PowerShell script to check a directory to see if any .ost files exist.
If it detects any .ost files I want it to run this code:
get-childitem "C:\Users\*" -include *.ost -recurse -force | foreach-object { remove-item $_ -force }
If it doesn't detect any .ost files I just want the script to exit.
Looking to add this to our startup scripts in group policy
Many thanks,Hi Tlewis4435,
In addition, please refer to the script below:
$files = get-childitem "D:\SHARE\*" -include *.ost -recurse -force
if($files){ #detect files
foreach($f in $files) { remove-item $f -force }
else{exit} #if there is no file then exit powershell
If there is anything else regarding this issue, please feel free to post back.
If you have any feedback on our support, please click here.
Best Regards,
Anna Wang
TechNet Community Support -
Powershell script monitor with encrypted password
I have created a powershell script based monitor in my management pack and everything is ok but I can't get my credentials work inside the script. I want to open pssession to another computer with my credentials. I have triple checked that my pssession is
working because I can access it from powershell console.
This works perfectly at local server from PSconsole:
$EncryptedPassword ="01000000d08c9ddf0115d1118c7a00c04fc297eb01000000534b2....etc...etc..."
$pw = convertto-securestring -String $EncryptedPassword
$cred = new-object System.Management.Automation.PSCredential -argumentlist "MyDOMAIN\MyACCOUNT",$pw
$s = New-PSSession -ComputerName "MyServer" -Port MyPort -Credential $cred
But when I run the same lines inside my management pack the convertto-securestring
does nothing, it just wont convert the encrypted password to secure string!
I have tried this plain text method and it works
inside my management pack, but I don't want to use it because you can see the password in plain text:
ConvertTo-SecureString -String "myPlainTextPassword" -AsPlainText -Force
This is the $error variable, so it's basically says that I don't have anything in the password secure string variable because the convertion did not work for some reason:
The argument is null. Provide a valid value for the argument, and then try running the command again. Cannot process argument transformation on parameter 'Credential'. PromptForCredential Exception calling ".ctor" with "2" argument(s):
"Cannot process argument because the value of argument "password" is null. Change the value of argument "password" to a non-null value." The system cannot find the file specified. Exception calling "SecureStringToBSTR"
with "1" argument(s): "Value cannot be null. Parameter name: s" The system cannot find the file specified. Exception calling "SecureStringToBSTR" with "1" argument(s): "Value cannot be null. Parameter name: s"
The system cannot find the file specified.
So is there some known issue with SCOM Agent / management pack when you are dealing with convertto-securestring
function with encrypted passwords?
I used these methods to encrypt the password: Technet article about encryptionI got it to work!
<TypeDefinitions>
<EntityTypes>
<ClassTypes>
<ClassType ID="MyClass" Accessibility="Public" Abstract="false" Base="Windows!Microsoft.Windows.LocalApplication" Hosted="true" Singleton="false" Extension="false"
/>
</ClassTypes>
</EntityTypes>
<SecureReferences>
<SecureReference ID="MyRunAsAccountProfile" Accessibility="Public" Context="System!System.Entity" />
</SecureReferences>
<ScriptBody>param (
[string]$Username,
[string]$Password
$API = new-object -comObject "MOM.ScriptAPI"
$PropertyBag = $API.CreatePropertyBag()
$cred = New-Object System.Management.Automation.PSCredential -Argumentlist @($Username,(ConvertTo-SecureString -String $Password -AsPlainText -Force))
$s = New-PSSession -ComputerName "myserver" -Credential $cred
Invoke-Command -Session $s -ScriptBlock { $service = Get-Service -Name Spooler}
$invcom = Invoke-Command -Session $s -ScriptBlock { $service.status}
Remove-PSSession -Id $s.Id
if ($invcom.Value -ne "Running") {
$PropertyBag.AddValue("State","ERROR")
$outputLongLine = "Spooler Service is not running on target server!"
$PropertyBag.AddValue("Description", $outputLongLine)
else {
$PropertyBag.AddValue("State","OK")
$outputLongLine = "Spooler is Running on target server."
$PropertyBag.AddValue("Description", $outputLongLine)
$PropertyBag</ScriptBody>
<Parameters>
<Parameter>
<Name>Username</Name>
<Value>$RunAs[Name="MyRunAsAccountProfile"]/Domain$\$RunAs[Name="MyRunAsAccountProfile"]/UserName$</Value>
</Parameter>
<Parameter>
<Name>Password</Name>
<Value>$RunAs[Name="MyRunAsAccountProfile"]/Password$</Value>
</Parameter> -
Using Echo Command in PowerShell Script for Configuration Item
Hello All,
Before you tell me to post my PowerShell question to the PowerShell Forum, please know that the PowerShell portion of my task works just fine. It is the SCCM portion of my task that keeps failing, so that is why I am here. To give some background...
There are two servers in our SCCM test environment. Both the SCCM server and SQL DB server are 2012, patched and updated.
Test servers in my Device Collection being used for running Baselines and Reports against are 2008R2 and 2012, patched and updated.
I have created a Configuration Item that checks to see if the FTP Server Role Feature has been installed on a 2008 or 2012 server. To do the check, I am using the following PowerShell script:
(get-windowsfeature -Name Web-Ftp-Server).Installed
When I log into my 2008R2 and 2012 test servers, and run this command directly on the server, it will return a "True" if the FTP Server Role Feature is installed on either server, and a "False" if it is not installed. Basically,
it works as advertised.
When I setup my Configuration Item and then deploy my Baseline, or run a report against my device collection of test servers, SCCM will return a correct response (True or False) for the 2012 test server, but throws the following error for the 2008R2
server:
0x87df00329 application requirement evaluation or detection failed
Google searches for this have not been very helpful.
Now, when I created the Configuration Item and referenced PowerShell, the configuration screen has the following note:
"Specify the script to find and return the value to be assessed for compliance on client devices. Use the echo command to return the script value to Configuration Manager."
Since I did not include an echo command in my PowerShell script above, I figured that was my problem, so I did the following:
Logging onto both of my test servers (2008R2 & 2012) I was able to successfully run the following PowerShell commands and get the expected responses of True or False:
(get-windowsfeature -Name Web-Ftp-Server).Installed | echo
(get-windowsfeature -Name Web-Ftp-Server).Installed | write-output (http://technet.microsoft.com/en-us/library/hh849921.aspx)
(get-windowsfeature -Name Web-Ftp-Server).Installed | write-host (http://technet.microsoft.com/en-us/library/ee177031.aspx)
However, when I use any of these PowerShell commands in my Configuration Item, NEITHER of my test servers returns a response to the SCCM server.
When I check the report, both servers show as "Unknown" and when I click on the number 2 (as in 2 servers unknown), the following report page (List of unknown assets for a configuration baseline) has absolutely no data/information at all.
So...I am at a loss.
SCCM tells me to use an echo command to return a script value to Configuration Manager. The PowerShell scripts above, with the various echo related commands, work just fine on the servers themselves, but they return no information when run via SCCM.
What am I missing?
Any help will be appreciated.
Thanks in advance for your time.Sorry for my ignorance, but I don't understand. (I forgot to mention that I am new at both PowerShell and SCCM.)
After I change the PowerShell script to add the echo/write-output/write-host cmdlet, I open the ConFig Item and "Clear" the PowerShell script and then re-add it. When I do that, it correctly shows the change in the ConFig Item.
Next I open the Baseline, then open the ConFig Item within the Baseline to make sure the change is reflected there as well, which it is.
I then deploy the Baseline to my Device Collection. After that, I run a report against the Baseline and Device Collection and it returns the "Unknown" result.
If I open the PowerShell script and remove the echo/write-output/write-host cmdlet, then go through the rest of the process of updating and reporting, the result it returns changes, showing one server in compliance and the other server out of compliance,
which leads me to think that all changes have taken correctly.
Does that sound right? If I manually deploy the Baseline, is that the same as the client retrieving policies from the management point?
Sorry to be so thick but I'm learning as I go.
Thanks again for your help. -
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 -
Need some help in building a PowerShell Script
I am in the process of setting up continuous self-auditing on a set of computers that are on a Domain. My company has a restriction on use of USB devices as well as CDs/DVDs. The domain pushes patches but we have been seeing some users that are using (or
trying to) the network without becoming a part of the domain. My aim is to run a PowerShell script periodically (say, hourly) on each computer on the domain and dump certain parameters to XML / XHTML and then load these onto a web-server that can display the
results in a (sort of) dashboard to flag anomalies like unauthorised USB use etc.
I know there must be some commercial products for this but the boss says "No" to a purchase.
Am I on the right track or do I need to change my approach? Also, is there a starting scirpt available somewhere so that I can study it for techniques? My major problem is the display part. I am able to dump it into XML and (sort of ) format it but how do
I collate the data and display it as a web-page is what is bothering me. Help would be deeply appreciated.@JRV:
Users don't have to be domain administrators
to be able to install software. Local admin is more than enough. ie: I am no admin in the domain of my customer but am allowed to install software
Although I agree with you, in the sense it would be easier to restrict the users, it doesn't mean that a company has to do it that way; and it certainly doesn't represent the intelligence of an individual.
@SarabRSingh:
What you are asking for is a lot of work, to get the script right (considering the special demands, ie. AV update checking is different depending on the SW) and it might require a lot of resources on the client.
From what you describe, you want to prevent any USB/Optical Media use. You should consider Group Policies to manage that. http://technet.microsoft.com/en-us/library/bb742376.aspx
The only part I would script (based on my work environment) is the checking of AV updates (gets tricky because our SW has a hard time forcing the user to update when connected by VPN).
user log in / out --> group policy: logon/off script writing appending timestamp to a file
has he/she used any USB device --> if you want to block it: GPO, if you only want to track it: powershell
Get-WmiObject Win32_USBControllerDevice
has any new application / software been installed: restrict installation completely with user permissions or: http://social.technet.microsoft.com/Forums/en-US/f4dc8ab9-370b-423e-b65d-1fa46fa9bcc4/powershell-script-to-remotely-audit-computers-on-lan?forum=ITCG
was the AV: no idea on what you are using (maybe: http://serverfault.com/questions/129611/how-to-detect-when-antivirus-is-out-of-date-with-powershell
OS updated: WSUS http://technet.microsoft.com/en-us/library/cc708519(v=ws.10).aspx
If you found this post helpful, please "Vote as Helpful". If it answered your question, remember to "Mark as Answer"
MCC & PowerShell enthusiast
http://oliver.lipkau.net/blog -
I am trying to run a PowerShell script to upload files into a SharePoint site in an Azure environment...the script works fine on my local machine, but every time I run it in Azure (remotely), I get errors. Here is what my simple script looks like...
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
Write-Host "Loading Sharepoint Module "
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
Add-PSSnapin -Name Microsoft.SharePoint.PowerShell
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell) -eq $null )
Write-Host "Failed to load sharepoint snap-in. Could not proceed further, Aborting ..."
Exit
#Script settings
$webUrl = "http://sampleWebUrl"
$docLibraryName = "My Documents"
$docLibraryUrlName = "My%20Documents"
$localFolderPath = get-childitem "C:\Upload\Test Upload\My Documents\" -recurse
$contentType = "ContenttType1"
#Open web and library
$web = Get-SPWeb $webUrl
write-host "Web:" $web
$docLibrary = $web.Lists[$docLibraryName]
write-host "docLibrary:" $docLibrary
$files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
write-host "files:" $files
If ($contentType = "ContenttType1")
#Open file
$fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()
# Gather the file name
$FileName = $File.Name
#remove file extension
$NewName = [IO.Path]::GetFileNameWithoutExtension($FileName)
#split the file name by the "-" character
$FileNameArray = $NewName.split("_")
$check = $FileNameArray.Length
#Add file
$folder = $web.getfolder($docLibrary.rootFolder.URL)
write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
$spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)
$spItem = $spFile.Item
write-host "Success"
write-host "SP File:" $spFile
write-host "SP Item" $spItem
#populate columns
$spItem["Column1"] = $FileNameArray[0]
$spItem["Column2"] = $FileNameArray[1]
$spItem.Update()
$fileStream.Close();
Again, I can run this on my local machine and it works just fine, but when I attempt to run it on the Azure environment I get this error...
Get-Item : Cannot find path 'C:\powershellscripts\12653_B7045.PDF' because it does not exist.
At C:\PowerShellScripts\Upload-FilesIntoSharePointTester.ps1:32 char:42
+ $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\powershellscripts\12653_B7045.PDF:String) [Get-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
What strikes me first is the fact that the file its looking for is in the "C:\Upload\Test Upload\My Documents\" directory, but the error keeps saying "C:\powershellscripts\" which is where my script resides and not the files I want to
upload into SharePoint. When I step through the code, all the variables are holding the correct values. The $localFolderPath shows the name of files that I am attempting to upload, so it recognizes them. But once I step through this particular line of code,
the error occurs...
$files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
Is this an error caused because I am remoting into the Azure environment? Has anyone dealt with this issue before? I would really appreciate the help. Thanks
Update: quick thing I noticed is that these two lines of code are returning null values. Again, is this handled differently in Azure or remotely? I ask cause this is the way I know how to do this, locally.
$docLibrary = $web.Lists[$docLibraryName]
$files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()"...square brackets are wildcard characters in Windows PowerShell..."
When you use cd without a parameter it uses the -Path parameter. In this case you'll have to escape the square brackets so they are not considered wildcards. Each of the commands in the first example does the exact same thing.
cd 'Learn PowerShell `[Do Whatever`]'
cd -Path 'Learn PowerShell `[Do Whatever`]'
cd (or Set-Location) also has a literal path parameter (-LiteralPath) that does not require using an escape character (`) before each of the brackets. Hope this helps.
cd -LiteralPath 'Learn PowerShell [Do Whatever]' -
Powershell script to get the low disk space on the servers...
Hi,
We have many SQL & Sharepoint servers running on windows server. I need some Powershell script to get the low disk space on those servers and it should send an mail alert saying "Disc d:\ have less than threshold 15% free space".
Awaiting for response.
Thanks
Anilyou should be able to use this powershell script which you can run as a scheduled task.
just change the details at the start of the script to point the script to the right location to create log files. you will need to have a plain text file containing a list of server names or ip addresses that you want to check drive space on.
# Change the following variables based on your environment
#specify the path to the file you want to generate containing drive space information
$html_file_dir = "\\server\share\DriveSpace"
#specify the path and file name of the text file containing the list of servers names you want to check drive space on - each server name on a seperate line in plain text file
$server_file = "\\server\share\servers.txt"
#speicfy the from address for the email
$from_address = "[email protected]"
#specify the to address for the email
$to_address = "[email protected]"
#specify the smtp server to use to send the email
$email_gateway = "smtp.domain.com" # Can either be DNS name or IP address to SMTP server
# The seventh line from the bottom (line 167) is used if your smtp gateway requires authentication. If you require smtp authentication
# you must uncomment it and set the following variables.
$smtp_user = ""
$smtp_pass = ""
# Change the following variables for the style of the report.
$background_color = "rgb(140,166,193)" # can be in rgb format (rgb(0,0,0)) or hex format (#FFFFFF)
$server_name_font = "Arial"
$server_name_font_size = "20px"
$server_name_bg_color = "rgb(77,108,145)" # can be in rgb format (rgb(0,0,0)) or hex format (#FFFFFF)
$heading_font = "Arial"
$heading_font_size = "14px"
$heading_name_bg_color = "rgb(95,130,169)" # can be in rgb format (rgb(0,0,0)) or hex format (#FFFFFF)
$data_font = "Arial"
$data_font_size = "11px"
# Colors for space
$very_low_space = "rgb(255,0,0)" # very low space equals anything in the MB
$low_space = "rgb(251,251,0)" # low space is less then or equal to 10 GB
$medium_space = "rgb(249,124,0)" # medium space is less then or equal to 100 GB
#### NO CHANGES SHOULD BE MADE BELOW UNLESS YOU KNOW WHAT YOU ARE DOING
# Define some variables
$ErrorActionPreference = "SilentlyContinue"
$date = Get-Date -UFormat "%Y%m%d"
$html_file = New-Item -ItemType File -Path "$html_file_dir\DiskSpace_$date.html" -Force
# Create the file
$html_file
# Function to be used to convert bytes to MB or GB or TB
Function ConvertBytes {
param($size)
If ($size -lt 1MB) {
$drive_size = $size / 1KB
$drive_size = [Math]::Round($drive_size, 2)
[string]$drive_size + ' KB'
}elseif ($size -lt 1GB){
$drive_size = $size / 1MB
$drive_size = [Math]::Round($drive_size, 2)
[string]$drive_size + ' MB'
}ElseIf ($size -lt 1TB){
$drive_size = $size / 1GB
$drive_size = [Math]::Round($drive_size, 2)
[string]$drive_size + ' GB'
}Else{
$drive_size = $size / 1TB
$drive_size = [Math]::Round($drive_size, 2)
[string]$drive_size + ' TB'
# Create the header and footer contents of the html page for output
$html_header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Server Drive Space</title>
<style type="text/css">
.serverName { text-align:center; font-family:"' + $server_name_font + '"; font-size:' + $server_name_font_size + `
'; font-weight:bold; background-color: ' + $server_name_bg_color + '; border: 1px solid black; width: 150px; }
.headings { text-align:center; font-family:"' + $heading_font + '"; font-size:' + $heading_font_size + `
'; font-weight:bold; background-color: ' + $heading_name_bg_color + '; border: 1px solid black; width: 150px; }
.data { font-family:"' + $data_font + '"; font-size:' + $data_font_size + '; border: 1px solid black; width: 150px; }
#dataTable { border: 1px solid black; border-collapse:collapse; }
body { background-color: ' + $background_color + '; }
#legend { border: 1px solid black; ; right:500px; top:10px; }
</style>
<script language="JavaScript" type="text/javascript">
<!--
function zxcWWHS(){
if (document.all){
zxcCur=''hand'';
zxcWH=document.documentElement.clientHeight;
zxcWW=document.documentElement.clientWidth;
zxcWS=document.documentElement.scrollTop;
if (zxcWH==0){
zxcWS=document.body.scrollTop;
zxcWH=document.body.clientHeight;
zxcWW=document.body.clientWidth;
else if (document.getElementById){
zxcCur=''pointer'';
zxcWH=window.innerHeight-15;
zxcWW=window.innerWidth-15;
zxcWS=window.pageYOffset;
zxcWC=Math.round(zxcWW/2);
return [zxcWW,zxcWH,zxcWS];
window.onscroll=function(){
var img=document.getElementById(''legend'');
if (!document.all){ img.style.position=''fixed''; window.onscroll=null; return; }
if (!img.pos){ img.pos=img.offsetTop; }
img.style.top=(zxcWWHS()[2]+img.pos)+''px'';
//-->
</script>
</head>
<body>'
$html_footer = '</body>
</html>'
# Start to create the reports file
Add-Content $html_file $html_header
# Retrieve the contents of the server.txt file, this file should contain either the
# ip address or the host name of the machine on a single line. Loop through the file
# and get the drive information.
Get-Content $server_file |`
ForEach-Object {
# Get the hostname of the machine
$hostname = Get-WmiObject -Impersonation Impersonate -ComputerName $_ -Query "SELECT Name From Win32_ComputerSystem"
$name = $hostname.Name.ToUpper()
Add-Content $html_file ('<Table id="dataTable"><tr><td colspan="3" class="serverName">' + $name + '</td></tr>
<tr><td class="headings">Drive Letter</td><td class="headings">Total Size</td><td class="headings">Free Space</td></tr>')
# Get the drives of the server
$drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=3" -ComputerName $_ -Impersonation Impersonate
# Now that I have all the drives, loop through and add to report
ForEach ($drive in $drives) {
$space_color = ""
$free_space = $drive.FreeSpace
$total_space = $drive.Size
$percentage_free = $free_space / $total_space
$percentage_free = $percentage_free * 100
If ($percentage_free -le 5) {
$space_color = $very_low_space
}elseif ($percentage_free -le 10) {
$space_color = $low_space
}elseif ($percentage_free -le 15) {
$space_color = $medium_space
Add-Content $html_file ('<tr><td class="data">' + $drive.deviceid + '</td><td class="data">' + (ConvertBytes $drive.size) + `
'</td><td class="data" bgcolor="' + $space_color + '">' + (ConvertBytes $drive.FreeSpace) + '</td></tr>')
# Close the table
Add-Content $html_file ('</table></br><div id="legend">
<Table><tr><td style="font-size:12px">Less then or equal to 5 % free space</td><td bgcolor="' + $very_low_space + '" width="10px"></td></tr>
<tr><td style="font-size:12px">Less then or equal to 10 % free space</td><td bgcolor="' + $low_space + '" width="10px"></td></tr>
<tr><td style="font-size:12px">Less then or equal to 15 % free space</td><td bgcolor="' + $medium_space + '" width="10px"></td></tr>
</table></div>')
# End the reports file
Add-Content $html_file $html_footer
# Email the file
$mail = New-Object System.Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($html_file)
$mail.From = $from_address
$mail.To.Add($to_address)
$mail.Subject = "Server Diskspace $date"
$mail.Body = "The diskspace report file is attached."
$mail.Attachments.Add($att)
$smtp = New-Object System.Net.Mail.SmtpClient($email_gateway)
#$smtp.Credentials = New-Object System.Net.NetworkCredential($smtp_user,$smtp_pass)
$smtp.Send($mail)
$att.Dispose()
# Delete the file
Remove-Item $html_file
Regards,
Denis Cooper
MCITP EA - MCT
Help keep the forums tidy, if this has helped please mark it as an answer
My Blog
LinkedIn: -
Powershell script to change the a column value of all documents in a site.
Hi,
I need a powershell script to change the value of a column (a site column which has been added to all document libraries) in all documents in a site,
For example:
-column 1 is a site column added to all libraries
the value of column 1 of all documents under this site: http://intranet.doman/ex1 should be equal to V1
the value of column 1 of all documents under this site: http://intranet.doman/ex2 should be equal to V2
So, if I can write a powershell script to change the value of all documents in a site, I can modify it for different site that I have and run it for each of them individually,cls
# Is dev version?
$dev = $false
# Configuration
$termStore = "Managed Metadata Service"
$group = "G1"
$subjectMatterTermSetName = "Subject Matter"
# Check if SharePoint Snapin is loaded
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Taxonomy") | Out-Null
function GetTermStore($site, $termStore, $group, $termSet) {
$session = New-Object Microsoft.SharePoint.Taxonomy.TaxonomySession($site)
$termStore = $session.TermStores[$termStore]
$group = $termStore.Groups[$group]
$termSet = $group.TermSets[$termSet]
return $termSet
if($dev) {
Write-Host "Running DEV version..."
$webUrl = "http://Site1"
$libraryName = "L1"
$subjectMatter = "C1"
} else {
$webUrl = Read-Host "Enter Site URL"
$libraryName = Read-Host "Enter Document Library name"
$subjectMatter = Read-Host "Enter Subject Matter"
try {
$web = Get-SPWeb $webUrl
$site = $web.Site
$library = $web.Lists[$libraryName]
$items = $library.GetItems()
$subjectMatterTermSet = GetTermStore $site $termStore $group $subjectMatterTermSetName
$subjectMatterTerm = $subjectMatterTermSet.GetTerms($subjectMatter,$true) | select -First 1
foreach($item in $items) {
if([string]::IsNullOrEmpty($item["Subject Matter"])) {
#Write-Host "Filename: $filename / Keywords: $keywords / Subject Matter: $subjectMatter / Document Type: $documentType"
Write-Host "Updating $($item["ows_FileLeafRef"])..."
# Set Subject Matter column
$subjectMatterField = [Microsoft.SharePoint.Taxonomy.TaxonomyField]$item.Fields["Subject Matter"]
$subjectMatterField.SetFieldValue($item,$subjectMatterTerm)
# Update Item
$item.SystemUpdate()
catch
$ErrorMessage = $_.Exception.Message
Write-Host "Something went wrong. Error: $ErrorMessage" -ForegroundColor Red -
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 - Convert Managed Metadata column Value to string
HI,
I have written a small PowerShell Script to pull records from a SP List and put them in a csv file. Here is the script:
$MyWeb = Get-SPWeb "http://dev-apps:8800/applications/PA"
$MyList = $MyWeb.Lists["Alist"]
$exportlist = @()
$Mylist.Items | foreach {
$obj = New-Object PSObject -Property @{
“PName” = $_["Port Name"]
"AName" = $_["Agent Name"]
"Address 1" = $_["Address 1"]
"Address 2" = $_["Address 1"]
"Address 3" = $_["Address 3"]
"Address 4" = $_["Address 4"]
$exportlist += $obj
$exportlist | Export-Csv -path 'C:\Filename.csv'
The script is running all right, the output file is also created, data is also correct for all columns but 1. This PName is a
Managed metadata type column and the output values I am getting for this column are like this:
"ERICA|a6d1e8fd-1f6b-4e09-9830-d21e35950881"
"CLIVE|24dff17f-a1b5-4abe-ae86-57299e1e098b"
viz. the ["Actual Value"|"its GUID"] (seems so). I do not want this GUID to be included in the result csv. Is there a way to remove it.
P.S. Choice column values are being fetched just file.Try this (you'll need to add in your other properties)
$items = New-Object psobject
$items | Add-Member -MemberType NoteProperty -Name "AName" -value "" ;
$items | Add-Member -MemberType NoteProperty -Name "PName" -value "" ;
$items | Add-Member -MemberType NoteProperty -Name "Address1" -value "" ;
$items | Add-Member -MemberType NoteProperty -Name "Address2" -value "" ;
$items | Add-Member -MemberType NoteProperty -Name "Address3" -value "";
$exportlist = @();
$Mylist.Items | foreach {
$pname = $_["PName"] -as [Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue];
$obj = $items | Select-Object *;
$obj.AName = $_["AName"];
$obj.PName = $pname.Label;
$obj.Address1 = $_["Address 1"];
$obj.Address2 = $_["Address 2"];
$obj.Address3 = $_["Address 3"];
$exportlist += $obj
$exportlist | Export-Csv -path 'C:\AData.csv'
Regards, Matthew
MCPD | MCITP
My Blog
View
Matthew Yarlett's profile
See my webpart on the TechNet Gallery that allows administrative users to upload, crop and format user profile photos. Check it out here:
Upload and Crop User Profile Photos -
How to export Powershell script information to Sharepoint?
I'm trying to export information gather from a Powershell script to a Sharepoint list. I've got a couple of powershell scripts that gather general server information from a server ex: server uptime, disk space, service tag, etc. and it will export the information
to a csv file. What I would like to do is out-put the same information gathered by the powershell scripts to a Sharepoint list directly if at all possible.
Ex:
# all this does is reads from a list and runs a script call "boottime.ps1"
get-content "\\%Data-Path-Of-List%\computers.txt" | %Data-Path-Of-Script%\boottime.ps1 | Export-csv %Data-Path-For-CSV\Computers.csv
# then just exports the information from the boottime.ps1 script to a csv file
#I also have a script that will upload the information to a sharepoint list.
# I found that I have to run this in version 2 of powershell, so I just open a DOS prompt in Admin Priv's and type the following
powershell.exe -version 2.0
# Next I make sure the Sharepoint snap-in is loaded
if ( (Get-PSSnapin -Name Microsoft.sharepoint.powershell - erroraction silentlycontinue) -eq $null)
Add-PsSnapin Microsoft.Sharepoint.Powershell
$spweb = get-SPweb $spserver
$spdata =$spweb.getlist("%URL_Of_My_List%")
# this is the same location from the orginal Powershell script previously stated.
$ComputerInfoFile = "%Data-Path-For-CSV%\Computers.csv"
foreach ($rows in $tblData) {
# here is where I add the information from my csv file
# 2 things needs to be present
# 1st the colums have to be present in the sharepoint site before I can upload the information
# 2nd the columns have to the headers in my csv file
$spItem = $spData.AddItem()
$SpItem["ServerName"] = $row."ServerName".toString()
$SpItem["Uptime"] = $row."Uptime".toString()
$SpItem.Update()
# this just disconnects from Sharepoint
$spWeb.Dispose()
Please dismiss all the comments it just helps me understand what the code is doing, also if this is not the correct place to post this question I appologize in adavance and ask that if this is the incorrect place to post this question please provide me a
link to a where I can post such questions.Sorry for the delay in posting this, but I ended up getting working. I'll post it in the hopes that my head scratching will save someone else some head scratching:
I ended up writting 3 PS scripts and one batch job.
1st Batch file
powershell.exe -version 2.0 -command
\\%Script-Location\Get-Server-Infor-4-SP.ps1
powershell.exe -version 2.0 -command \\%Script-Location\Delete-list-Items.ps1"
powershell -veriosn 2.0 -command
\\%Script-Location\Populate-SP.ps1
1st PS script that gets the info:
get-content
\\%Location-Of-My-File-With-List-Of-Servers%\%name-of-file%.txt |
\\%Location-Of-My-Script-To-get-the-Information-I-want | Export-csv
\\%location-of-my-output\%filename%.csv
Ex: get-content C:\scripts\computers.txt | C:\scripts\boottime.ps1 | export-csv C:\scripts\computer.csv
2nd PS script Delete-List-Items.ps1
# http:
#Script 1 Boottime.ps1:
# This script permits to get UpTime from localHost or a set of remote Computer
# usage
# localHost
# .\BootTime.ps1
# set of remote computers
# get-content .\MyserverList.txt | .\boottime.ps1
# Optionally pipe output to Export-Csv, ConverTo-Html
Process {
$ServerName = $_
if ($serverName -eq $Null) {
$serverName= $env:COMPUTERNAME
$timeVal = (Get-WmiObject -ComputerName $ServerName -Query "SELECT LastBootUpTime FROM Win32_OperatingSystem").LastBootUpTime
#$timeVal
$DbPoint = [char]58
$Years = $timeVal.substring(0,4)
$Months = $timeVal.substring(4,2)
$Days = $timeVal.substring(6,2)
$Hours = $timeVal.substring(8,2)
$Mins = $timeVal.substring(10,2)
$Secondes = $timeVal.substring(12,2)
$dayDiff = New-TimeSpan $(Get-Date –month $Months -day $Days -year $Years -hour $Hours -minute $Mins -Second $Secondes) $(Get-Date)
$Info = "" | select ServerName, Uptime
$Info.servername = $servername
$d =$dayDiff.days
$h =$dayDiff.hours
$m =$dayDiff.Minutes
$s = $daydiff.Seconds
$info.Uptime = "$d Days $h Hours $m Min $s Sec"
$Info
#Script 2: Delete-List-Items.ps1
# http://markimarta.com/sharepoint/delete-all-items-in-sharepoint-list-using-powershell/
# there seems to be a problem with running this script in version 3 or later, the workaround is to run it in version 2
# below is the cmd for doing so, just open up a DOS prompt with Admin Privileges Start-->Run-->cmd
# type then copy and paste the following line the DOS window then you can run this script
#powershell.exe -version 2.0
# make sure that the Microsoft.SharePoint.PowerShell Snap-in is installed as well
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
Add-PsSnapin Microsoft.SharePoint.PowerShell
# "Enter the site URL instead http://serverurl"
$SITEURL = "%http://serverurl%"
$site = new-object Microsoft.SharePoint.SPSite ( $SITEURL )
$web = $site.OpenWeb()
"Web is : " + $web.Title
# Enter name of the List below in the [“%List-Name%”]
$oList = $web.Lists["%List-Name%"];
# This echo out the name of the list its going to be deleting the records from
"List is :" + $oList.Title + " with item count " + $oList.ItemCount
# It’s just counting the rows/records
$collListItems = $oList.Items;
$count = $collListItems.Count - 1
# Here is where it is actually deleting the records and then out put the number or the record it deleted
for($intIndex = $count; $intIndex -gt -1; $intIndex--)
"Deleting record: " + $intIndex
$collListItems.Delete($intIndex);
#Script 3: Populate-SP_Test.ps1
# http://blogs.technet.com/b/stuffstevesays/archive/2013/07/10/3577320.aspx
# there seems to be a problem with running this script in version 3 or later, the workaround is to run it in veriosn 2
# below is the cmd for doing so, just open up a DOS prompt with Admin Privileges Start-->Run-->cmd
# type then copy and paste the following line the the DOS window then you can run this script
#powershell.exe -version 2.0
# make sure that the Microsoft.SharePoint.PowerShell Snap-in is installed
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
Add-PsSnapin Microsoft.SharePoint.PowerShell
# Here are some more varables that can be added I was not able to get this to work
#$SPComputerInfo="/Lists/PowershellTest/"
# Here is where we connect and Open SharePoint List via Powershell
$SPServer= "%http://serverurl%
$spWeb = Get-SPWeb $SPServer
$spData = $spWeb.GetList("%List-Name%")
# This is the variable for the path that has the file I want to input to SharePoint List
$InvFile="\\%location-ofList%\computers.csv"
# This is just some error checking to make sure the file exist
$FileExists = (Test-Path $InvFile -PathType Leaf)
if ($FileExists) {
"Loading $InvFile for processing..."
$tblData = import-csv $InvFile
} else {
"$InvFile not found - stopping import!"
exit
# Loop through Applications add each one to SharePoint
"Uploading data to SharePoint...."
foreach ($row in $tblData) {
#Here is where I add the information from my CSV file
#2 things have to be present
# 1. the columns have to be in the sharepoint site before I can import the information
# 2. columns have to the headers in my csv file
#"Adding entry for "+$row."Computer Information".ToString()
$spItem = $spData.AddItem()
$spItem["ServerName"] = $row."ServerName".ToString()
$spItem["Uptime"] = $row."Uptime".ToString()
#$spItem["DNSHostName"] = $row."DNSHostName".ToString()
#$spItem["DistinguishedName"] = $row."DistinguishedName".ToString()
$spItem.Update()
# This is just disconnecting from SharePoint
$spWeb.Dispose()
Enjoy, and if anyone has a better way of doing this I'm interested in knowing, thanks again
Thanks in Adavance
Maybe you are looking for
-
Error while creating material master
hi, I'm getting this error message when I'm creating a material master in a specific plant/sloc. I'm probably guessing its in config. I really need some help here. "Tables TCURM and T001W inconsistent; notify your system administrator" . could any on
-
[solved] Tearing Problem / Refresh Rate
Hey, i have a huge tearing problem. Watching movies is a real torture. I think it's the refresh rate. The recommended refresh rate for my display is 60Hz (@1920x1080p). But i can only choose 50Hz in the XFCE settings (link). Anyone can say how to cha
-
What's the point of buying apps from the BBWorld?
What's the point of purchasing apps from the BlackBerry world for playbook if I don't even know if they will work after the BB10 update?
-
Flash audio bug on Firefox Mozilla on PC
- Quoted from Bugzilla@mozilla: https://bugzilla.mozilla.org/show_bug.cgi?id=289873 To see the problem, go to http://www.spellingcity.com User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6) Gecko/20050317 Firefox/1.0.2 Build Identif
-
Question about LabVIEW generated DLL's
Hello, I want to try programming games in either JAVA or FLASH. What I want to know is if I can use the LabVIEW generated DDL's for use in my games, without having to need the LabVIEW runtimes installed. (in other words, are the LabVIEW generated DLL