Help with powershell
Hi,
I'm new with powershell. I have a simple txt file with one line and numerisk value.
I need a script that runs every day and change this value with -1.
exp. The value is always in line 1
old value - 20140115
shuld be after script run: 20140114
so I need replace the "old value" with "old value-1)
Robert
Hello Thanks for respond, unfortunately
this script is not working for me, see below what i got.
PS C:\> { (Get-Content -Path $file -ErrorAction Stop) -1 |
>> Out-File $file -Force -ErrorAction Stop}catch{ Write-Error "$_"
>> }
>>
Unexpected token 'catch' in expression or statement.
At line:2 char:46
+ Out-File $file -Force -ErrorAction Stop}catch <<<< { Write-Error "$_"
+ CategoryInfo : ParserError: (catch:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
PS C:\>
Similar Messages
-
Help with Powershell - moving files to folders based on date
I have spent about a week on this task, and I know I am nowhere near an expert on Powershell, I am running into a wall.
Here is what I want to accomplish - I have a folder with 1000's of files going back three years. I want to write a PS script that will move all the files older than three months into archive folders based on the file creation date. I need two levels, Year
and inside the year, month.
Here is what I have so far
$location = "C:\scripts\Test1"
cd $location
dir | ?{$_.psiscontainer -eq $false}| %{$a="$($_.creationtime.year.ToString())";mkdir -ea 0 $a;mv $_ $a}
$locationYear = "C:\Scripts\Test1\$a"
cd $locationYear
dir | ?{$_.psiscontainer -eq $false}| %{$b="$($_.creationtime.month.ToString())";mkdir -ea 0 $b;mv $_ $b}
I know its basic, but it is working so far, except the folder month is in numeral format, 3 not 03. This is a requirement from our development team.
Any help would be appreciated, Thanks!JVR- thank you as well, I keep getting strange results. It looks like it makes the folders for 2014 but then starts erroring - it should be looking in the scripts/pdf folder, not the scripts folder.
Move-Item : Cannot find path 'C:\scripts\2014-05-23 - XXXXX - report.pdf' because it does not exist.
At C:\scripts\scriptomovetocreationdatefolderNEW.ps1:6 char:3
+ Move-Item $_ $newdir
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\scripts\2014...62 - report.pdf:String) [Move-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand
$location = "C:\scripts\pdfs"
dir $location -File |
ForEach-Object{
$Fldr='{0}\{1}\{2:D2}' -f $location, $_.CreationTime.Year,$_.CreationTime.Month
$newdir=$dir=New-Item $fldr -ItemType Directory -force
Move-Item $_ $newdir -
I have an powershell commando that pulls all my machines of xenapp 7.6 that are registered.
But i want my script to show me output when an machine is unregistered. Can any one help me out with the if and else statement.
This is for registered machines:
Get-BrokerMachine | select MachineName, RegistrationState | Where { $_.RegistrationState -eq 'Registered' }
Th is for Unregistered servers:
Get-BrokerMachine | select MachineName, RegistrationState | Where { $_.RegistrationState -eq 'UnRegistered' }
Output is like this:
MachineName
RegistrationState
XXX\wsgrswxa01
Registered
XXX\wsgrswxa02
Registered
XXX\wsgrswxa03
Registered
I tried a little bit with if and else statement. But i don't know how to do it.
(example):
if(?)
echo “OK status – All XenApp machines or OK”
exit 0 #Return OK status
else
echo “CRITICAL status – These Machines(xxxx,xxxx) are Unregistered”
exit 2 #returns critical status
Can anyone help me out?Hi,
you do that by 1) saving the query for unregistered machines, 2) Checking whether there are any unregistered Machines from that variable and 3) Writing down the names (again from the variables).
Cheers,
Fred
oh, ok, here you go :)
$Machines = Get-BrokerMachine | Where { $_.RegistrationState -eq 'UnRegistered' }
if (($Machines | Measure-Object).Count -gt 0)
Write-Output "CRITICAL status – These Machines ($(($Machines | Select-Object -ExpandProperty MachineName) -join ",")) are Unregistered"
exit 2
else
Write-Output "OK status – All XenApp machines or OK"
exit 0
There's no place like 127.0.0.1 -
Help with Powershell script to gather eventlogs from all Domain Controllers
I am trying to write a script to grab the last 5 days of application, security and system logs from all domain controllers. The script runs but only pulls the logs from the local server. The $Computer variable has all of my DC's so it is querying fine. I
assume it is an issue with my ForEach-Object line but it doesn't error out. See the script below.
$log = "Application"
$date = get-date -format MM-dd-yyyy
$now = get-date
$subtractDays = New-Object System.TimeSpan 5,0,0,0,0
$then = $Now.Subtract($subtractDays)
$Computers = Get-ADDomainController -filter *
ForEach-Object -InputObject $Computers -Process {Get-EventLog -LogName $log -After $then -Before $now -EntryType Error | select EventID,MachineName,Message,Source,TimeGenerated | ConvertTo-html | Out-File $env:TEMP\Applicationlog.htm}
Invoke-Expression $env:TEMP\Applicationlog.htm
Thanks,
RichAlso, you're missing the -ComputerName parameter in the Get-EventLog Cmdlet.
I would re-write the loop part of the script like this:
$log = "Application"
$date = get-date -format MM-dd-yyyy
$now = get-date
$subtractDays = New-Object System.TimeSpan 5,0,0,0,0
$then = $Now.Subtract($subtractDays)
$Computers = Get-ADDomainController -filter *
foreach ($Computer in $computers) {
Get-EventLog -ComputerName $Computer -LogName $log -After $then -Before $now -EntryType Error |
select EventID,MachineName,Message,Source,TimeGenerated | ConvertTo-html | Out-File .\Applicationlog.htm -append
Invoke-Expression .\Applicationlog.htm
Sam Boutros, Senior Consultant, Software Logic, KOP, PA http://superwidgets.wordpress.com (Please take a moment to Vote as Helpful and/or Mark as Answer, where applicable) -
Help with PowerShell to delete a date range of Calendar meetings
I'm trying to delete all Calendar items within a date range, from a mailbox. But first I'd like to just make sure my date filter is actually working.
Here is what i HAVE working:
Search-Mailbox ME -SearchQuery "Received:01/01/2010..03/18/2010" -EstimateResultOnly
This works, it gives me a count of all things in my mailbox
Search-Mailbox ME -SearchQuery kind:meetings -EstimateResultOnly
This works, it gives me a count of all Meetings in my Calendar.
I reallly need now to get the date range to work in conjunction with the kind:meetings.
How can I do that?Hi,
The results include the deleted meetings. I test it in my lab.
So the command to delete Calendar meetings with a date range is this:
Search-Mailbox "username" -SearchQuery "Received:01/01/2010..3/18/2015 kind:meetings" –EstimateResultOnly -DeleteContent
Best Regards.
Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact [email protected]
Lynn-Li
TechNet Community Support -
Looking for help with PowerShell script to delete folders in a Document Library
I'd like to create a PowerShell script to delete old folders in a Document library that are over 30 days old. Has anyone created something like this?
Orange County District AttorneyHello Sid:
I am trying to do the same and Iam running the script to delete the subfolders inside a folder but I have some errors.
Could you please take a look?
_______Script________
$web = Get-SPWeb -Identity https://myportal.mydomain.com
$list = $web.GetList("ar_mailingactivity")
$query = New-Object Microsoft.SharePoint.SPQuery
$camlQuery = '<Where><And><Eq><FieldRef Name="ContentType" /><Value Type="Computed">Folder</Value></Eq><Leq><FieldRef Name="Created" /><Value Type="DateTime"><Today OffsetDays="-30" /></Value></Leq></And></Where>'
$query.Query = $camlQuery
$items = $list.GetItems($query)
for ($intIndex = $items.Count - 1; $intIndex -gt -1; $intIndex--)
$items.Delete($intIndex);
________Errors_______
Unable to index into an object of type System.Management.Automation.PSMethod.
At C:\Script.ps1:2 char:22
+ $list =$webGetList <<<< "ar_mailingactivity"]
+ CategoryInfo
:InvalidOperation: (ar_mailingactivity:String) [], RuntimeException
+ FullyQualifiedErrorID
:CannotIndex
You cannot call a method on a null-valued expression.
At c:\Script.ps1:6 char:24
+ $items = $list.GetItems <<<< ($query)
+ CategoryInfo
:InvalidOperation: (GetItems:String) [], RuntimeException
+ FullyQualifiedErrorID
:InvokeMethodOnNull -
Creation of SharePoint Search service with the help of powershell.
Hi Team,
Upgraded WSS 3.0 to SharePoint 2013 Foundation red the SharePoint search.
We found log backup on the subjected server was failing due to database name,
which is more than max allowed legth. To fix the same, we may need to rename the
same to short name.
failed-1073548784)
Executing the query "BACKUP LOG [Search_Service_Application_AnalyticsRe..."
failed with the following error: "Invalid device name. The length of the
device name provided exceeds supported limit (maximum length is:259). Reissue
the BACKUP statement with a valid device name.
BACKUP LOG is terminating
abnormally."
Database Name :
Search_Service_Application_AnalyticsReportingStoreDB_2e7b13e23fde4c8397ed0be06474966f
To rename SharePoint Search it took more than 5 hours.
Is it possible to create SharePoint search using PowerShell and will get support from Microsoft for search application built this way ?
Please share information on how create SharePoint search using powershell.
Our environment: SharePoint 2013 Foundation.
Best Regards,
MaheshHi Mahesh,
To create Search Service Application in SharePoint Foundation 2013 by using PowerShell, you can refer to the links below for more details:
http://www.andrewjbillings.com/sharepoint-2013-foundation-creating-the-search-service-with-powershell-and-removing-those-pesky-guids/
http://blog.falchionconsulting.com/index.php/2013/02/provisioning-search-on-sharepoint-2013-foundation-using-powershell/
Best regards,
Victoria Xia
TechNet Community Support
Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
[email protected] -
How to manage a connection with powershell using visual studio with C#
Hi
I want to manage a connection with powershell for a web app using visual studio with c#. and also run command with pipeline
Plz give a some suggestions..Hi Raj_Kumar_Saini,
To make things clear, could you please clarify these thing?
1. Do you mean you want to execute some PowerShell scripts from C# language? These blogposts may give you some ideas:
Executing PowerShell scripts from C#
Powershell Automation and Remoting (a c# love story)
Execute PowerShell from a ASP.NET Web Application
2. Is your question related to Visual Studio Integration? Do you want to build a Visual Studio Extension?
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.
Click
HERE to participate the survey. -
Read Outlook Email and Get Specific Content from Mail with PowerShell
Hi Everyone,
I would like to get full content value by searching in mail body with PowerShell but I stuck at one place in scripting and would required help from your side. Below is my script with description.
#Connecting Outlook with below command
$Outlook = New-Object -ComObject Outlook.Application
# Now getting all folders info in variable (Shows Email, Calendar, Tasks etc)
$OutlookFolders = $Outlook.Session.Folders.Item(1).Folders
#Now connecting Inbox mails
$OutlookInbox = $Outlook.session.GetDefaultFolder(6)
#Now reading latest mail
$latestmail=$OutlookInbox.items | select -last 1
#Now calling email content and getting email content as output in html
$latestmail.HTMLBody
#below is output
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<META NAME="Generator" CONTENT="MS Exchange Server version 14.00.0004.000">
<TITLE></TITLE>
</HEAD>
<BODY>
<!-- Converted from text/plain format -->
<P><FONT SIZE=2><A HREF="https://test.abc.com/sys/servlet/ViewFormServlet?f
orm=NTE%3aNotifier&server=sm.user&eid=NTS000299462947">https://test.abc.com/sys/servlet/ViewFormServlet?form=NTE%3aNotifier&server=sm.user&eid=NTS4556555
294437</A><BR>
<BR>
Incident IND000008655308 has been assigned to your group 'Windows
ADMINISTRATION'.<BR>
Company: ABC<BR>
Customer Name: XYZ<BR>
Service Type: Infrastructure Event<BR>
Priority: High<BR>
SLA Resolve Target Status: Within the Service Target<BR>
SLA Response Target Status:<BR>
Reported Source: Systems Management<BR>
*******************************************************************<BR>
Summary: server1.abc.com: Average (5 samples) total cpu is now 100.0
0%, which is above the error t<BR>
<BR>
*******************************************************************<BR>
Notes: server1.abc.com: Average (5 samples) total cpu is now 100.00%
, which is above the error threshold (100%)</FONT></P>
</BODY>
</HTML>
# Now my target is to search incident number which is starting from IND* and server name (server1.abc.com). I tried below code but not getting value. Please help me to get these two values from email.
$latestmail.HTMLBody -match "IND"
#Output
True
#but not getting full that is IND000008655308.
Please help me.Try this:
if($latestmail.HTMLBody -match 'IND(?<x>\d+)\S'){
$value='IND'+$matches['x']
}else{
Write-Host 'Not found'
\_(ツ)_/ -
How to create an azure website with PowerShell?
Hello
I'm, trying to create a new wordpress website in Azure with PowerShell, I saw a video: https://www.youtube.com/watch?v=LHjkn59Lf0g
But, When execute my code, I get the following error:
New-AzureResourceGroup :
06:42:41 p. m. - Resource SuccessBricks.ClearDB/databases 'dbdb3' failed with message 'User
failed validation to purchase resources. Error message: '["Credit Card is the only supported payment instrument for
purchases"]''
What Can I do?
I have a bizspark subscription with enough money :S
THANKS!Hi Victor,
Thanks for your question.
Firstly, I recommend you to create the website and recourse group in Azure portal to see if the issue persists.
In addition, I will have a test for this and feedback to you later. Appreciate your patience.
Best regards,
Susie
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] -
DFS V2 setting ABE with Powershell
Hello everybody
we currently have a stand-alone DFS running on W2K8R2 without replication. Inside our central namespace the access based enumeration is enabled. In former times we create a dfs-share with dfscmd.exe for and used dfsutil.exe for setting the abe. This
works very fine.
Now I tried this with powershell:
new-dfsnfolder creates the share as expected.
grant-dfsnaccess seems to works without an error.
But the share itself still has "use inheritance permissions from local filesystem" instead of "set explicit permissions on the dfs Folder" and is viewable for everybody. Switching inside the gui to "explicit permission" shows
the permissions given with grant-dfsnaccess.
Has anybody an idea how to switch this Setting?
Best regards from Germany GuidoHi Guido,
It seems that you have encounter the issue described in this article:
The Windows PowerShell cmdlet Grant-DfsnAccess does not change inheritance on DFS links
This is because although the Grant-DfsnAccess cmdlet successfully configures the view permissions for individual groups or users, the cmdlet does not change the inheritance mode from use inherited to set explicit.
To work around this problem, use one of the following method:
dfsutil property sd grant \\Contoso.com\Software\Projects Contoso\SarahJones:RX protect
If there is anything else regarding this issue, please feel free to post back.
Best Regards,
Anna Wang
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 Support, contact [email protected] -
Create a Loolup field with PowerShell but Change the Default Display field
Hi
I am creating the a load of site columns with PowerShell. In the case of a Lookup Column I want to ensure that a the the industry column is checked programmatically.
$myField.LookupList = $spLookupList.ID
$myField.LookupField = $LookUpmyField.InternalName
As you can see there is no provision for a display name (Industry) which I want to display to the user once they select a lookup column
I just know somebody is going to suggest CAML !!!! Btw the code works but none of the checkboxes are selected as expected.
Daniel
Freelance consultantI tried a same in past. Couldn't find a perfect code. You can try below:
http://blogs.msdn.com/b/varun_malhotra/archive/2008/06/19/how-to-set-the-default-value-for-a-look-up-field-for-an-item-as-it-is-being-created.aspx
<Code>
SPList docs = w.Lists["Documents"];
SPFieldLookup fl = (SPFieldLookup)docs.Fields["City"];
fl.DefaultValue = "1;#Mexico City";
fl.Update();
</Code>
http://social.msdn.microsoft.com/Forums/sharepoint/en-US/afd71aa8-54d3-424f-9b72-67328e080048/update-lookup-field-powershell?forum=sharepointdevelopmentprevious
$w = Get-SPWeb http://web
$l = $w.Lists["MyDocumentLibrary"]
$lf = $l.Fields["lookupColumn"]
$i = $l.Items[0] #List item to update
$lf.ParseAndSetValue($i,"1;#lookupvalue") #1;#lookupvalue refers to the ID of the lookup item and the value of the lookup item.
$i.Update()
If this helped you resolve your issue, please mark it Answered -
Deleting Stale Office 365 online Mailboxes with Powershell
We are using Office 365 online for our student email system.
I want to remove any mailbox that hasn't been accessed in the last year.Once you determine that, you can remove the mailboxes a number of ways - depending on how your onsite AD interacts with Office 365.
If you use DirSync, the users that have been deleted onsite should eventually be purged from Office 365, mailboxes included.
*To be honest, I have always deleted users manually using the method below, so I cannot affirm, from experience, that this is the case, so someone may correct me.*
You can manaully purge mailboxes as well (I had to do this a while ago) with PowerShell cmdlets.
$cred = get-credential
connect-msolservice -credential $cred
Remove-MsolUser –UserPrincipalName [email protected]
Yes, you have to install what is known as the Windows Azure Active Directory Module for PowerShell to use those commands (cmdlets).
http://technet.microsoft.com/en-us/library/jj151815.aspx
If that's not clear, please ask follow up questions.
Please mark as helpful if you find my contribution useful or as an answer if it does answer your question. That will encourage me - and others - to take time out to help you. -
Right click on script"run with PowerShell"
I have set the execution policy in GPO to remoteSigned, and it is working fine, when I run the script from cmd prompt powershell –f
When I right click the script and choose “run with PowerShell” it starts with this text in red
Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope.
Due to the override, your shell will retain its current effective executionpolicy of RemoteSigned
The script is working, but it do not look right for a user of the script.
Sometimes when I run the script “run with PowerShell” it prompts the user to overwrite policy, again no matter if I choose yes or no, the script will run.
I am running on Windows 8.1 Update 1 x64, Powershell 4.0
Do anyone know how to fix?
Kind Regards
Jens
Jens LundThere is another Group Policy setting that is setting a different policy. Post in the GP forum to get help with fixing this.
Possibility #2. You are setting the policy in your profile or on the command line.
¯\_(ツ)_/¯ -
SCOM 2012 Get Gray Management Servers With PowerShell
Hi,
I have SCOM 2012 R2.
I want to get all the Management Servers that are in Gray state using powershell. How can I do that?
I couldn't find anything good in the internet.
The best I got was Get-SCOMManagementServer but when I tested it out - it still showed that my gateway's HealthState was "Success" even though it was gray.
Thanks,
Yakir.Hi,
Check if this one helps
Get-SCOMClass-name"Microsoft.SystemCenter.ManagementServer"|get-scomclassinstance|selectdisplayname,healthstate
I dont what is your final objective, but check this link
http://blogs.technet.com/b/jasonrydstrand/archive/2013/03/27/daily-scom-health-check-with-powershell.aspx
Maybe you are looking for
-
List View in Finder having issues
When I try to save to a network drive with Photoshop CS 2 in list view, Photoshop crashes. When I try to open folders in list view in Dreamweaver on a network drive, I only get drop-downs, the folder doesn't actually open. I seem to have no problem s
-
There was a link on mozilla web page. The link was located on the bottom of the page, but it seams that its no longer there
-
Change page margins to print email
Is there any way to change the page margins when printing emails? When I print out an email, the page margins are a good 1" on top, left and bottom so I have to reduce the type in order to keep simple emails on one sheet of paper.
-
[BUG] Removed source photos: cannot "Cancel all"
It's more a missing feature than a bug, however I just reopened iPhoto after months, just to try out the new version (I'm a Lightroom user). Long time ago I exported an album to take a look of the software and explore its features. After months those
-
Hi. I'm migrate to Exchange 2013. I moved mailbox, moved public folders ( 20 folders in one pf-mailbox). I can see structure public folders, but when i send mail to public folders, i see error: this recepient not found Формирующий сервер: EXCHANGE201