Powershell Script to copy mobilephone number to telephone number
Hello Friends,
I need a powershell script to copy mobilephone attribute to telephone attribute.
Scenario is below:
I have Group "Test1" , I need to copy mobilephone attribute to telephone attribute of all the uses in this Group.
I have created the script but its not giving desired result
"Get-QADGroup "test1"|
ForEach-Object{
Get-QADGroupMember$_.samaccountname}|
selectsamaccountname,mobilephone
| export-csvD:\test1.csv
Import-Csv "D:\test1.csv"|
%{Get-QADUSer$_.Samaccountname
| Set-QADUser-ObjectAttributes@{telephonenumber=$_.mobilephone}}"
My observation:
1.while I exporting the attribute , i am not getting proper telephone format in CSV which is "+919999XXX1111"
2. If Telephonenumber attribute of a user is allready filled , it does not update the attribute. it only update the attribute if it is blank
Plase help to resolve it.
this is kind of urgent , thank you all in advance
Thank you for your reply
but it is not changing anything however scripts executes perfectly.
I want to add one more thing here when i export the "mobilePhone" attribute it comes in the format "9.2E+11"
whereas it should come in the format "+919999XXX111".
So, as i said earlier if "telephonenumber" fields remains blank it takes the value "9.2E+11" which is error. but it is not replacing if fileld has some value and value format is not correct.
Similar Messages
-
Powershell Script to Copy an Unknown number of Files in a Directory
I need to be able to copy an unknown number of files in a folder to an FTP site. I have the FTP components figured out and working, but am running into a problem when there is only 1 file for upload. The folder is a queue that users manually
copy files to, so i do not have control of how many files may be pending. And the file names are always different.
My script performs the following steps.
1. Get a list of files in the directory with the a attribute. (this prevents subfolders from being processed)
2. Loop thru the list, copying each file.
Here is my problem.
no files. nothing happens. normal and expected
2 or more files. all files upload correctly. EXPECTED
Filename returned from variable = "True". File does not exist and upload fails. ERROR
This is what the script looks like. (There are several Write-Output statements for debugging purposes.
$ftpUploadPath = "$ftpServer/claims/"
$localUploadPath = "$localDir\claims\"
$localSentPath = "$localUploadPath`Sent\"
$listFile = "$localDir\uplist.txt"
Write-Output "Uploading Claim files to $ftpUploadPath ..."
#1 get list of claim files to upload
$list = Get-ChildItem -Name $localUploadPath -Attributes a
Write-Output $list
Write-Output " "
#2 loop thru list and upload files
if($list.Length -ne 0){
#Write-Output " Getting files from list"
# download each file in the list
foreach ($file in $list -cne "") {
Write-Output $file
} # end foreach file
} #end if($list.Length)
else {
Write-Output " No files for upload"
} #end else($list.Length)
Thanks in advance,
GregYou are writing way too many lines for such a simple task. Try this:
Get-ChildItem -Name $localUploadPath -Attributes a |
ForEach-Object{
Write-Host $_ -fore green
$_
\_(ツ)_/ -
Using WEBDAV in a Windows PowerShell script
Hello,
I am trying to write a Windows PowerShell script to copy a file from my SharePoint site to a DB repository folder using a WEBDAV link. I am not getting it to work.
When I copy from SharePoint to SharePoint it works. I have used my credentials on the script which has the authorizations but it still isn't working. The response error is a 500 Internal Server error.
Any ideas?
Has anyone done this before?
Thanks,
MattThis is not a solution but more an extra tool to help you find a solution....
You could download and install the Portal Drive to see what actions/commands are used to communicate via webdav to the KM repository.
Cheers,
B -
Powershell script to count number of list and library items in site collection
We are identifying large lists in our 2010 SP environment and I'm attempting to write code to output the total number of list items in a site collection. I'm using the code below but it only displays column data for title and url.
What do I need to add so it can count the number of items in each sharepoint list and library?
Get-SPSite -WebApplication http://sharepoint -Limit All |
Select -ExpandProperty AllWebs |
Select -ExpandProperty Lists |
Select ParentWebUrl, Title
I'm referencing
http://sharepointpromag.com/sharepoint/windows-powershell-scripts-sharepoint-info-files-pagesweb-partsPlease find belwo script, it will iterarte through all the folder/Subfoder to get the item counts from all list and library, you can modify this script to run this at site collection scope:
Note: save the script in .ps1 file and execute the script as described below to get log file, it will save the log file out.txt in seleted directory:
e.g.PS D:\PowershellScripts> .\ListItemCount.ps1 > out.txt
$SPWebApp = Get-SPWebApplication "http://weburl.com/"
foreach ($SPSite in $SPWebApp.Sites)
if ($SPSite -ne $null)
foreach ($SPWeb in $SPSite.AllWebs)
foreach ($list in $SPWeb.Lists)
$ListURL = $SPWeb.url + "/" + $list.RootFolder.Url
Write-Output $ListURL
[Microsoft.SharePoint.SPQuery]$query = New-Object Microsoft.SharePoint.SPQuery
#$query.Folder = fldr;
#Recursive Scope....
$query.ViewAttributes = "Scope='Recursive'"
$allitems = $list.GetItems($query);
$filecount = $allitems.Count;
Write-Output " No of item: " $filecount
if ($SPWeb -ne $null)
$SPWeb.Dispose()
if ($SPSite -ne $null)
$SPSite.Dispose()
You can update the code to get any specific list type item count, using if($list.BaseType -eq "DocumentLibrary") condition:
if($list.BaseType -eq "DocumentLibrary")
$ListURL = $SPWeb.url + "/" + $list.RootFolder.Url
Write-Output $ListURL
[Microsoft.SharePoint.SPQuery]$query = New-Object Microsoft.SharePoint.SPQuery
#$query.Folder = fldr;
#Recursive Scope....
$query.ViewAttributes = "Scope='Recursive'"
$allitems = $list.GetItems($query);
$filecount = $allitems.Count;
Write-Output " No of item: " $filecount
if ($SPWeb -ne $null)
$SPWeb.Dispose()
If my contribution helps you, please click Mark As Answer on that post and Vote as Helpful
Thanks, ShankarSingh -
How to copy a folder from TFS source control to Shared location with Powershell script
Hi,
I'm looking for a Powershell script where i could copy a folder from TFS Source control to a shared location.
Details:
$TeamProject/FolderA - here i want to move FolderA to a shared location called \\Share
Tried with xcopy: xcopy "$TeamProject/FolderA" "\\Share" ( but no luck, later i found it's only possible to copy files from local to share or share to share location, not from server path to shared location.
Can someone help me with the power-shell script to achieve above scenario.
Thanks, BHSRHope the below script works for your scenario. Got the code from http://stackoverflow.com/questions/23739499/copy-files-from-tfs-versioncontrol-to-directory-with-powershell
$AutoDeployDir = "$\TeamProject/FolderA"
$deployDirectory = "\\SERVER\SHAREFOLDER\"
# Add TFS 2013 dlls so we can download some files
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.VersionControl.Client")
$tfsCollectionUrl = "http://CDTFSSERVER:8080/tfs/ProjectCollection"
$tfsCollection = New-Object -TypeName Microsoft.TeamFoundation.Client.TfsTeamProjectCollection -ArgumentList $tfsCollectionUrl
$tfsVersionControl = $tfsCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
# Register PowerShell commands
Add-PSSnapin Microsoft.TeamFoundation.PowerShell
# Get all directories and files in the AutoDeploy directory
$items = Get-TfsChildItem $AutoDeployDir -Recurse -Server $tfsCollection
# Download each item to a specific destination
foreach ($item in $items) {
# Serverpath of the item
Write-Host "TFS item to download:" $($item.ServerItem) -ForegroundColor Blue
$destinationPath = $item.ServerItem.Replace($AutoDeployDir, $deployDirectory)
Write-Host "Download to" $([IO.Path]::GetFullPath($destinationPath)) -ForegroundColor Blue
if ($item.ItemType -eq "Folder") {
New-Item $([IO.Path]::GetFullPath($destinationPath)) -ItemType Directory -Force
else {
# Download the file (not folder) to destination directory
$tfsVersionControl.DownloadFile($item.ServerItem, $([IO.Path]::GetFullPath($destinationPath)))
Regards, Bharath
LinkedIn: -
Number of windows servers reboot time through PowerShell scripting
This code is using for one server ----Get-WmiObject win32_operatingsystem | select csname, @{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}
How to get more than one server reboot time through PowerShell scripting?
cheers
uday#Method 1#When you have few servers which you can quicly type
'localhost' , 'localhost' | %{Get-WmiObject win32_operatingsystem |
select csname, @{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}}
#Mehod 2#When you have huge list you can make csv with header and use $_.headername
Import-CSV C:\Temp\Serverlist.csv | %{Get-WmiObject win32_operatingsystem -ComputerName $_.ServerName |
select csname, @{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}}
#Method 3
#Same as method 2 but using text file
$pc = Get-Content C:\Temp\Serverlist.txt
foreach($server in $pc){
Get-WmiObject win32_operatingsystem -ComputerName $server |
select csname, @{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}
Regards Chen V [MCTS SharePoint 2010] -
How to change maintenance powershell script via GPO?
Per suggestion reposted from here: http://social.technet.microsoft.com/Forums/windowsserver/en-US/6eece9d6-a524-48aa-8e64-7554f0ec9b31/how-to-change-maintenance-powershell-script-via-gpo?forum=winserverGP
Posted at http://answers.microsoft.com/en-us/windows/forum/windows_7-desktop/desktop-shortcuts-to-items-on-network-drives/94eddb27-342b-40fc-9ad4-677ff4ee8ebe?page=9&tm=1403700614489 originally.
There is a very annoying "feature" in Windows 7 called BrokenShortcuts.ps1 which is being called out weekly via maintenance task and if it finds more than 4 "broken" network shortcuts it removes them all. So it means if a user at this
moment is disconnected from the network he will lose all links to shares, network applications sitting on his desktop. Funny that there was no such script on Vista and i don't see this on Win8. On the post i have attached one user suggested to edit this script
and change 4 to 500 or whatever high number. That's fine for one time fix. But i need to do this for 200+ users. This file cannot be simply replaced by a script, so i'm wondering is there any way to do it via GPO?
I have already tried various startup scripts, but i'm not sure which user to put into commands.
I need to run this on startup:
takeown /F C:\Windows\diagnostics\scheduled\Maintenance\TS_BrokenShortcuts.ps1
icacls c:\windows\diagnostics\scheduled\maintenance\TS_BrokenShortcuts.ps1 /grant "some user":F
copy \\share\folder$\TS_BrokenShortcuts.ps1 C:\Windows\diagnostics\scheduled\Maintenance\ /YYou need to take time to study how Windows does these things. You can control them with GP which is what you asked. The article shows you how to disable elements of the tasks. Each task controls a script. If you disable the task the
script that deletes shortcuts will be stopped. Other maintenance tasks will continue to run.
Most of your problem is that you seem to want someone to provide a magical solution. In technology it is necessary to fully research your issues until you understand all aspects. After fully studying the issue you should understand the possible
solutions if they exist.
You claim to have deployed the patch that Microsoft released to fix the issue. You claim it didn't work. If that is the case then you need to call MS and \p[en a support incident. If Microsoft determines that you are right about the
patch not working you will not be charged for the call.
I know that learning how to support technology is hard and frustrating for newcomers. In time, by using these incidents to learn, you will become a seasoned technician and all of this will seem trivial. Until then we can only suggest that you
do things that most of us are familiar with. We cannot fix your network for you.
I think you haven't really posted in the GP forum but posted a question about GP in the server forum. Try posting in the GP forum.
http://social.technet.microsoft.com/Forums/windowsserver/en-US/home?forum=winserverGP
Here is one answer from the GP forum:
http://social.technet.microsoft.com/Forums/windowsserver/en-US/home?forum=winserverGP
http://social.technet.microsoft.com/Forums/windowsserver/en-US/600ca14f-8b1b-400c-b27f-a7f5733407ac/windows-scheduled-maintenance-task?forum=winserverGP
¯\_(ツ)_/¯ -
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 -
MDT WinPE TSEnv variables and pathing some powershell scripts.
Hi again everyone!
I have a question about running some powershell scripts inside of MDT. Now I know that you can create a powershell command in the task sequence, and that will create the proper elevations and such, but I would like some organization here. I have
been creating my OS modification scripts inside of an Image Utilities folder under applications and then calling them with a powershell.exe windowstyle -hidden script.ps1. The scripts will run, but I have alot of custom unpackaged stuff that I'm trying
to quickly move and create on the freshly deployed OS. My issue comes in with using things like copy-item .\items -destination c:\itemdest\ . I have a folder that I created with some items that need to be in the OS image process, plus the
powershell script. I was thinking maybe I could do some sort of set unc=%~dp0 or something and make a $env:unc or something, but I was hoping someone might've solved this already. Thanks in advance for any help.
RyanHi Ryan,
Sorry but you're not being clear enought for me. I usually need things dumbing down for me to understand. :)
=%~dp0 is the current folder. I'll assuming from that, you're trying to get the same thing in PowerShell.
There's a number of ways depending of what you're trying to do.
$PWD is usefull from the command line
The $MyInvocation object holds a wealth of info from the path to the executable/function used.
There's a blog on it here How can a script tell what directory it was run from?
Also, the best place for help on this kind of thing is the scripting guys forum. I hope this puts you in the right direction.
/Andrew
Blog: http://scriptimus.wordpress.com -
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. -
An unknown error occurred while executing the PowerShell script:
Hello all,
Not the most descriptive title, granted. I'm hoping this may prompt the next version toprovide additional valuable content.
Kindly requesting any help on this problem. I'm running VMM 2012 R2 version 3.2.7668
When I try to look at properties of an existing Private Cloud, I get this error, only if I "look" at certain attributes. If I stay away from the specific attributes, everything is hunky dory. For reasons unknown, after I get this error, I have
to exit and go back into VMM in order to get anything else to run.
The text in the error dialogue box is not entirely applicable because I was connected to the VMM server and will connect again, when I exit/relaunch.
An unknown error occurred while executing the PowerShell script:
The connection to the VMM management server scvmm2.mmmmmm.com was lost.
Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager service is started
on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
Try the operation again. If the issue persists, contact Microsoft Help and Support.
ID: 27235
This is what I get in Events
Warning 4/9/2015 3:27:04 PM PowerShell (Microsoft-Windows-PowerShell) 4100 Executing Pipeline
Log Name: Microsoft-Windows-PowerShell/Operational
Source: Microsoft-Windows-PowerShell
Date: 4/9/2015 3:27:04 PM
Event ID: 4100
Task Category: Executing Pipeline
Level: Warning
Keywords: None
User: mmmmmm\paufra
Computer: tools-francis.mmmmmm.com
Description:
Error Message = The connection to the VMM management server scvmm2.mmmmmm.com was lost. (Error ID: 1610)
Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager service is started
on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
Fully Qualified Error ID = 1610,Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.GetSCReplicationGroupCmdlet
Recommended Action = Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager
service is started on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
Context:
Severity = Warning
Host Name = Default Host
Host Version = 4.0
Host ID = 94963cd4-5979-4786-9da2-c8814de8c7c3
Host Application = C:\Program Files\Microsoft System Center 2012 R2\Virtual Machine Manager\Bin\VmmAdminUI.exe
Engine Version = 4.0
Runspace ID = 359d7a46-3752-4929-8c09-0de4152d10e4
Pipeline ID = 16
Command Name = Get-SCReplicationGroup
Command Type = Cmdlet
Script Name =
Command Path =
Sequence Number = 91
User = mmmmmm\paufra
Shell ID = Microsoft.PowerShell
User Data:
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="Microsoft-Windows-PowerShell" Guid="{A0C1853B-5C40-4B15-8766-3CF1C58F985A}" />
<EventID>4100</EventID>
<Version>1</Version>
<Level>3</Level>
<Task>106</Task>
<Opcode>19</Opcode>
<Keywords>0x0</Keywords>
<TimeCreated SystemTime="2015-04-09T22:27:04.993655700Z" />
<EventRecordID>285</EventRecordID>
<Correlation ActivityID="{48059811-1A63-41E1-9057-7498D0E4FC20}" />
<Execution ProcessID="2344" ThreadID="4076" />
<Channel>Microsoft-Windows-PowerShell/Operational</Channel>
<Computer>tools-francis.mmmmmm.com</Computer>
<Security UserID="S-1-5-21-4008432563-1984933819-4238309236-2721" />
</System>
<EventData>
<Data Name="ContextInfo"> Severity = Warning
Host Name = Default Host
Host Version = 4.0
Host ID = 94963cd4-5979-4786-9da2-c8814de8c7c3
Host Application = C:\Program Files\Microsoft System Center 2012 R2\Virtual Machine Manager\Bin\VmmAdminUI.exe
Engine Version = 4.0
Runspace ID = 359d7a46-3752-4929-8c09-0de4152d10e4
Pipeline ID = 16
Command Name = Get-SCReplicationGroup
Command Type = Cmdlet
Script Name =
Command Path =
Sequence Number = 91
User = mmmmmm\paufra
Shell ID = Microsoft.PowerShell
</Data>
<Data Name="UserData">
</Data>
<Data Name="Payload">Error Message = The connection to the VMM management server scvmm2.mmmmmm.com was lost. (Error ID: 1610)
Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager service is started
on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
Fully Qualified Error ID = 1610,Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.GetSCReplicationGroupCmdlet
Recommended Action = Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager
service is started on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
</Data>
</EventData>
</Event>Hi Sir,
First , please try to run the VMM configuration analyzer on that computer :
http://www.microsoft.com/en-us/download/details.aspx?id=41555
In addition , please try to use "VMMTrace" mentioned in following article to collect trace log and find some useful information :
http://blogs.technet.com/b/jonjor/archive/2011/01/07/vmmtrace-simplified-scvmm-tracing.aspx
Best Regards,
Elton Ji
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected] . -
How to Compare 2 CSV file and store the result to 3rd csv file using PowerShell script?
I want to do the below task using powershell script only.
I have 2 csv files and I want to compare those two files and I want to store the comparision result to 3rd csv file. Please look at the follwingsnap:
This image is csv file only.
Could you please any one help me.
Thanks in advance.
By
A Path finder
JoSwa
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful"
Best Online JournalNot certain this is what you're after, but this :
#import the contents of both csv files
$dbexcel=import-csv c:\dbexcel.csv
$liveexcel=import-csv C:\liveexcel.csv
#prepare the output csv and create the headers
$outputexcel="c:\outputexcel.csv"
$outputline="Name,Connection Status,Version,DbExcel,LiveExcel"
$outputline | out-file $outputexcel
#Loop through each record based on the number of records (assuming equal number in both files)
for ($i=0; $i -le $dbexcel.Length-1;$i++)
# Assign the yes / null values to equal the word equivalent
if ($dbexcel.isavail[$i] -eq "yes") {$dbavail="Available"} else {$dbavail="Unavailable"}
if ($liveexcel.isavail[$i] -eq "yes") {$liveavail="Available"} else {$liveavail="Unavailable"}
#create the live of csv content from the two input csv files
$outputline=$dbexcel.name[$i] + "," + $liveexcel.'connection status'[$i] + "," + $dbexcel.version[$i] + "," + $dbavail + "," + $liveavail
#output that line to the csv file
$outputline | out-file $outputexcel -Append
should do what you're looking for, or give you enough to edit it to your exact need.
I've assumed that the dbexcel.csv and liveexcel.csv files live in the root of c:\ for this, that they include the header information, and that the outputexcel.csv file will be saved to the same place (including headers). -
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]' -
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.
Maybe you are looking for
-
Itunes wont launch, no error message, no blue screens, just wont open
itunes wont launch, i get no error message, no blue screen, it just wont open. I've tried to delete and reinstall, but once i close itunes i still have same issue. it wont open again.
-
Unknown site error while deploying web services using OC4J
Hi, I have been testing the deploying webservices examples using demo.zip on OTN site. I have trouble in binding the web application name to stand alone OC4J. I am running stand alone OC4J server fine. I verified the website http://localhost:8888, wh
-
To whom it may concern. I bought an apple product which is MacBook Air about 7 mths. ago . Anyway I would like to download a compatible words, excel, powerpoint. they told me that I do not need it since IWORKS is all I needed. I tried my keynote , nu
-
[solved] firefox and flash
From today I doesn't see flash video in firefox. Any idea? Last edited by ugaciaka (2011-05-03 17:57:16)
-
Get inbound delivery number by using material serial number
is anyfuction module to get inbound delivery number by using material serial number? input---material serial number. output--inbound delivery number.