Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
tango alpha delta
Sep 9, 2011

Ask me about my wealthy lifestyle and passive income! I love bragging about my wealth to my lessers! My opinions are more valid because I have more money than you! Stealing the fruits of the labor of the working class is okay, so long as you don't do it using crypto. More money = better than!
I love Powershell and I'm here to tell you why:

We have a team of 1000 developers who regularly release a new version of their vertical. It's huge. We are a SOX shop, so one of the controls is that the developers cannot branch their own code. We do the branching.

They send us an Excel spreadsheet with all the versions they need branched.

I wrote a Powershell script to extract the versions and convert them into SVN branch commands. My script also updates the Excel spreadsheet with the new branch numbers. The best part is that this is all automated. We create a change request and roll out the branches into production without any problems.

EDIT: To accomplish the same thing in C# is loving painful and not worth the effort.

tango alpha delta fucked around with this message at 04:27 on Aug 3, 2014

Adbot
ADBOT LOVES YOU

Malcolm XML
Aug 8, 2009

I always knew it would end like this.

tango alpha delta posted:

I love Powershell and I'm here to tell you why:

We have a team of 1000 developers who regularly release a new version of their vertical. It's huge. We are a SOX shop, so one of the controls is that the developers cannot branch their own code. We do the branching.

They send us an Excel spreadsheet with all the versions they need branched.

I wrote a Powershell script to extract the versions and convert them into SVN branch commands. My script also updates the Excel spreadsheet with the new branch numbers. The best part is that this is all automated. We create a change request and roll out the branches into production without any problems.

EDIT: To accomplish the same thing in C# is loving painful and not worth the effort.

Sounds like you came up with a good solution to an insane problem.

TheEffect
Aug 12, 2013
I'm trying to create a PowerShell script that will send a Lync message to all users in column "A" the text in columns "B" and "C".

I started out using this guide- http://blogs.technet.com/b/csps/archive/2011/05/05/sendim.aspx

I believe I have most of the framework down, but my main issue is figuring out how to actually IM the user. When I run my script I get

"Cannot find an overload for "AddParticipant" and the argument count: "1"."

Here's what I have so far (the million try statements were to help troubleshoot).

e; updated broken code.

TheEffect fucked around with this message at 21:27 on Aug 6, 2014

ElGroucho
Nov 1, 2005

We already - What about sticking our middle fingers up... That was insane
Fun Shoe

tango alpha delta posted:

I love Powershell and I'm here to tell you why:

We have a team of 1000 developers who regularly release a new version of their vertical. It's huge. We are a SOX shop, so one of the controls is that the developers cannot branch their own code. We do the branching.

They send us an Excel spreadsheet with all the versions they need branched.

I wrote a Powershell script to extract the versions and convert them into SVN branch commands. My script also updates the Excel spreadsheet with the new branch numbers. The best part is that this is all automated. We create a change request and roll out the branches into production without any problems.

EDIT: To accomplish the same thing in C# is loving painful and not worth the effort.

I hope you are claiming this is taking you hours of work, and then playing Zuma's Revenge all day

along the way
Jan 18, 2009
Okay, can someone help me with this one, because I'm just not getting it.

Basically, I just want to grab the current AD group membership of one user and apply the same group membership to another user, so, grab the groups that user jdoe1 is a member of and add user jdoe2 to those same groups.

code:
(Get-ADPrincipalGroupMembership jdoe1 | Select-Object -Property SamAccountName)
Produces a list of the security groups to which user jdoe1 belongs.

Running it through

code:
(Get-ADPrincipalGroupMembership jdoe1 | Select-Object -Property SamAccountName) | gm
Produces TypeName "ADGroup"

code:
TypeName: Selected.Microsoft.ActiveDirectory.Management.ADGroup
Okay, that's good because the -Identity parameter of the Add-ADGroupMember command accepts input by value for type ADGroup, right?

code:
help Add-ADGroupMember -full

-Identity <ADGroup>

Required?                    true
        Position?                    1
        Default value                
        Accept pipeline input?       true (ByValue)
        Accept wildcard characters?  false
So, why is it that when I try to pipe the output of Get-ADPrincipalGroupMembership to Add-ADGroupMember that I get a conversion error:

code:
$jdoe1_groups = (Get-ADPrincipalGroupMembership jdoe1 | Select-Object -Property SamAccountName)

Add-ADGroupMember -Identity $jdoe1_groups -Members jdoe2

Add-ADGroupMember : Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADGroup' 
required by parameter 'Identity'. Specified method is not supported.
At line:1 char:29
+ Add-ADGroupMember -Identity $jdoe1_groups -Members jdoe2
+                             ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Add-ADGroupMember], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMem 
   ber
Is it because the ADGroup member type being produced by Get-ADPrincipalGroupMembership | Select-Object is Selected.Microsoft.ActiveDirectory.Management.ADGroup and not Microsoft.ActiveDirectory.Management.ADGroup which is what it appears the Add-ADGroupMember parameter is looking for?

I'm pretty new to PowerShell and I'm working my way through Learn PS in a Month of Lunches book, so sorry if this is a dumb question with a really obvious answer.



Edit: Okay, I got it working by using the ForEach-Item cmdlet and running $jdoe1_groups through Get-ADGroup first:

code:
$jdoe1_groups = Get-ADPrincipalGroupMembership -Identity jdoe1

$jdoe1_groups | ForEach-Item {Add-ADGroupMember -Identity (Get-ADGroup $jdoe1_groups) -Members jdoe2}
I'm having a hard time wrapping my head around why this works, but I think it's because:

1. $jdoe1_groups contains an array and thus requires ForEach-Item for iterative processing
2. Add-ADGroupMember -Identity parameter requiring Get-ADGroup to produce the appropriate object type

Hoping someone can help further clarify what's going on here if I'm not on the right track.

along the way fucked around with this message at 16:18 on Aug 5, 2014

orange sky
May 7, 2007

I want to change all contacts in all Outlook clients in my company. I want to get rid of middle names and put them all Firstname=Firstname, Lastname=Middle+Lastname. Can I do this with Powershell or should I go vbscript? Thanks in advance.

TheEffect
Aug 12, 2013

TheEffect posted:

I'm trying to create a PowerShell script that will send a Lync message to all users in column "A" the text in columns "B" and "C".

I started out using this guide- http://blogs.technet.com/b/csps/archive/2011/05/05/sendim.aspx

I believe I have most of the framework down, but my main issue is figuring out how to actually IM the user. When I run my script I get

"Cannot find an overload for "AddParticipant" and the argument count: "1"."

Here's what I have so far (the million try statements were to help troubleshoot).

e; updated broken code.

Updated my code and re-framed the question with some clarification. Not sure why this isn't working; every guide I look at online seems to match what I have for the most part. Can't for the life of me figure out why I'm getting that error. This question appears similar but it has no real solution:

http://stackoverflow.com/questions/19254906/exception-calling-beginsendmessage-with-3-arguments-value-does-not-fall

I'm not even sure how useful this application will be (why wouldn't you just create a group and then ask via group chat whatever information you needed?) but goddamn am I determined to get it working.


Edit-

Got a bit further with this. Apparently "AddParticipant" does not want a string but a URI. So I changed my code to convert via

$contact = $LyncClient.ContactManager.GetContactByUri("yourperson@domain.com")
$Convo.AddParticipant($contact)

however now I'm getting "Exception calling "GetContactByUri" with "1" argument(s): "Value does not fall within the expected range."

The exception is-

NotSpecified: (:) [], MethodInvocationException

TheEffect fucked around with this message at 17:21 on Aug 7, 2014

12 rats tied together
Sep 7, 2006

capitalpunctuation posted:

Can't see anything in event viewer to clue me in to what's going on. All the googling says remotely executing msi files, or batch files, is trivially easy, but I've followed a hundred tutorials to no avail. What am I missing?

Just a guess but you're probably running into the problem outlined in this article: http://technet.microsoft.com/en-us/magazine/jj853299.aspx

quote:

I'm having a hard time wrapping my head around why this works, but I think it's because:

1. $jdoe1_groups contains an array and thus requires ForEach-Item for iterative processing
2. Add-ADGroupMember -Identity parameter requiring Get-ADGroup to produce the appropriate object type

Hoping someone can help further clarify what's going on here if I'm not on the right track.
You basically figured it out. Sort of. $jdoe1_groups probably doesn't "technically" contain an array, but it does need to be iterated through. Your script is a little messy looking to me (not that it matters, though) and could probably be cleaned up with some dot sourcing. I can't really tell without testing, and I don't have an AD environment at home, but to me it looks like:

code:
$jdoe1_groups | ForEach-Item {Add-ADGroupMember -Identity (Get-ADGroup $jdoe1_groups) -Members jdoe2}
Is double-iterating on you. At a glance, what appears to be happening is that it takes each item of jdoe1_groups and does an add-adgroupmember -identity (all of the groups in jdoe1_groups) -members jdoe2.

This might not be the case with ForEach-Item (I almost always use ForEach-Object), but generally I've found that you can force iteration by doing "$Variable | ForEach-Whatever {do thing}", or if the commands "play nice", you can do a "Do-Thing -Identity(Get-Thing)", and it will iterate through that way. You should enable debug mode (select a line in the ISE, make sure the script is saved to disk, hit F9) and step through the script a few times to make sure it isn't double-iterating on you.

I've also found that generally $variable = get-object | select SomeProperty doesn't behave the way you think it does. $Variable probably still refers to the object returned by Get-Object, not the properties returned by Select-Object. So, you most likely specifically Select-Objected into GM and got ADGroup, when in actuality the $variable was still referring to the parent object that contains a child object that is an AD group. That probably explains your Object -> ADGroup conversion error. Try piping into get-member without doing the Select-Object and see if it still returns an ADGroup.

along the way
Jan 18, 2009

Reiz posted:

You basically figured it out. Sort of. $jdoe1_groups probably doesn't "technically" contain an array, but it does need to be iterated through. Your script is a little messy looking to me (not that it matters, though) and could probably be cleaned up with some dot sourcing. I can't really tell without testing, and I don't have an AD environment at home, but to me it looks like:

code:
$jdoe1_groups | ForEach-Item {Add-ADGroupMember -Identity (Get-ADGroup $jdoe1_groups) -Members jdoe2}
Is double-iterating on you. At a glance, what appears to be happening is that it takes each item of jdoe1_groups and does an add-adgroupmember -identity (all of the groups in jdoe1_groups) -members jdoe2.

This might not be the case with ForEach-Item (I almost always use ForEach-Object), but generally I've found that you can force iteration by doing "$Variable | ForEach-Whatever {do thing}", or if the commands "play nice", you can do a "Do-Thing -Identity(Get-Thing)", and it will iterate through that way. You should enable debug mode (select a line in the ISE, make sure the script is saved to disk, hit F9) and step through the script a few times to make sure it isn't double-iterating on you.

I've also found that generally $variable = get-object | select SomeProperty doesn't behave the way you think it does. $Variable probably still refers to the object returned by Get-Object, not the properties returned by Select-Object. So, you most likely specifically Select-Objected into GM and got ADGroup, when in actuality the $variable was still referring to the parent object that contains a child object that is an AD group. That probably explains your Object -> ADGroup conversion error. Try piping into get-member without doing the Select-Object and see if it still returns an ADGroup.

Yeah, I noticed the double iteration and changed the (Get-ADGroup $jdoe_groups) portion to read from the variable being piped in with (Get-ADGroup $_).

Also, I goofed on filling in ForEach-Item when I meant ForEach-Object. I was actually using the alias foreach in the PS prompt and filled it in mistakenly after the fact.

Thanks for the clarifications. Like I said, I'm just starting out with Powershell with my only scripting experience being with batch files up until recently, so stuff like dot sourcing is a little beyond me for now.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
How do I code for Sharepoint list queries via CSOM when I'm told that I can only retrieve X number of rows per query? I've never worked with that kind of constraint before - do I perform multiple queries until the database says "you've reached the end" and push everything into some kind of holding array?

For example, take the following query that limits me to 200 rows per query:

code:
function getLookupValues($_ctx, $_listName, $_colToMatch)
{
	$lookupList = $_ctx.Web.Lists.GetByTitle($_listName)
	$query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery(200, 'ID', $_colToMatch)
	$vals = $lookupList.getItems($query)
	$_ctx.Load($lookupList)
	$_ctx.Load($vals)
	$_ctx.ExecuteQuery()
	
	return $vals
}
How do I modify this to pull everything if $_listName has greater than 200 rows?

TheEffect
Aug 12, 2013

TheEffect posted:

Got a bit further with this. Apparently "AddParticipant" does not want a string but a URI. So I changed my code to convert via

$contact = $LyncClient.ContactManager.GetContactByUri("yourperson@domain.com")
$Convo.AddParticipant($contact)

however now I'm getting "Exception calling "GetContactByUri" with "1" argument(s): "Value does not fall within the expected range."

With help from someone on another forum I was able to find the solution to my problem. Posting here in case anyone else was interested-

I stepped through and outputted $UserName each time the code touched it and I figured out that $UserName.Trim() only OUTPUTS the trimmed string and does not store it (of course!), so I changed it to $UserName = $UserName.Trim() and everything is working beautifully.

What was happening was I was taking "lastname, firstname" from a cell in Excel and formatting it so that it would be "firstname.lastname@domain.com" but due to there being a space after the comma I had to use .trim() to get rid of it, but I never considered how .trim() worked and so the variable was retaining the space character.

ConfusedUs
Feb 24, 2004

Bees?
You want fucking bees?
Here you go!
ROLL INITIATIVE!!





Hey, I have a question. Pardon me if it's basic. I've done some very minor powershell scripting but I'm not an expert by any means.

I work with backup software, and I serve as a top escalation point for our support staff. If they get stuck they gather some logs from the customers' machines. I regularly have to search event logs for specific, backup-related events.

Searching event logs in the Event Viewer is slow as hell. Seriously it's awful.

Can powershell scan saved event logs and pull out individual events based on various criteria?

For example, take this basic VSS event:

Log Name: Application
Source: VSS
Date: 8/14/2014 10:03:30 AM
Event ID: 8224
Task Category: None
Level: Information
Keywords: Classic
User: N/A
Computer: MX-DC.robbinstbm.com
Description:
The VSS service is shutting down due to idle timeout.

Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="VSS" />
<EventID Qualifiers="0">8224</EventID>
<Level>4</Level>
<Task>0</Task>
<Keywords>0x80000000000000</Keywords>
<TimeCreated SystemTime="2014-08-14T15:03:30.000000000Z" />
<EventRecordID>801229</EventRecordID>
<Channel>Application</Channel>
<Computer>MX-DC.robbinstbm.com</Computer>
<Security />
</System>
<EventData>
<Data>
</Data>
</EventData>
</Event>

Could I have powershell scan the event log, find anything from Source: VSS, and print the results to a text file?

Could I do the same based upon text in the Description section?

Could I define a date range for this? Say, last 7 days?

CLAM DOWN
Feb 13, 2007




Two ways to do that as I know:

code:
Get-EventLog -LogName Application | where source -eq "VSS"
But that cmdlet is pretty limited. You can also use:

code:
Get-WinEvent -FilterHashtable @{logname='Application';providername='VSS';starttime="1/8/14";endtime="7/8/14"} | Out-File C:\Temp\output.txt
This will give you all VSS events in the application event log from 1 Aug to 7 Aug and output it to C:\Temp\output.txt.

Does that help at all?

ConfusedUs
Feb 24, 2004

Bees?
You want fucking bees?
Here you go!
ROLL INITIATIVE!!





CLAM DOWN posted:

Two ways to do that as I know:

code:

Get-EventLog -LogName Application | where source -eq "VSS"

But that cmdlet is pretty limited. You can also use:

code:

Get-WinEvent -FilterHashtable @{logname='Application';providername='VSS';starttime="1/8/14";endtime="7/8/14"} | Out-File C:\Temp\output.txt

This will give you all VSS events in the application event log from 1 Aug to 7 Aug and output it to C:\Temp\output.txt.

Does that help at all?

That's about 10x easier than I expected. Is it possible to grab any event that includes a word in the description?

CLAM DOWN
Feb 13, 2007




ConfusedUs posted:

That's about 10x easier than I expected. Is it possible to grab any event that includes a word in the description?

code:
Get-WinEvent -FilterHashtable @{logname='Application';providername='VSS';starttime="5/1/14";endtime="8/1/14"} | where message -match "Volume Shadow Copy Service error" | Out-File C:\Temp\output.txt
I modified the datestamps for May to Aug 2014 for American date formats as I am making the terrible assumption you are American like a lot of IT posters on SA, mine was D/M/Y before.

The above gives me an output file that looks something like:

code:
   ProviderName: VSS

TimeCreated                     Id LevelDisplayName Message                                        
-----------                     -- ---------------- -------                                        
7/28/2014 2:30:42 PM         12293 Error            Volume Shadow Copy Service error: Error call...
7/23/2014 8:33:37 PM         12293 Error            Volume Shadow Copy Service error: Error call...
7/10/2014 8:11:00 PM         12293 Error            Volume Shadow Copy Service error: Error call...
7/7/2014 5:57:18 PM          12293 Error            Volume Shadow Copy Service error: Error call...
6/2/2014 8:24:44 PM          12293 Error            Volume Shadow Copy Service error: Error call...
5/26/2014 8:17:18 PM         12293 Error            Volume Shadow Copy Service error: Error call...
5/15/2014 8:15:46 PM         12293 Error            Volume Shadow Copy Service error: Error call...
5/2/2014 8:40:58 PM          12293 Error            Volume Shadow Copy Service error: Error call...


vvv No problem!

CLAM DOWN fucked around with this message at 01:00 on Aug 15, 2014

ConfusedUs
Feb 24, 2004

Bees?
You want fucking bees?
Here you go!
ROLL INITIATIVE!!





That rocks. I can adapt that easily for my needs. Thank you!

Hughmoris
Apr 21, 2007
Let's go to the abyss!
I need to accomplish a task and I'm thinking powershell might be my only hope.

I need to schedule a task on 10 VMs, but I need to have it specific to a second. For example, at 08:40:15 I want to launch notepad.exe on VM1. Then at 08:40:20 I want to launch notepad.exe on VM2. Ideally, I'd like to sit at my workstation and use powershell to schedule the tasks.

What I have been doing is using the taskscheduler GUI but its clunky and takes forever to work my way through 10 VMs. I've tried learning more about SCHTASKS in command prompt but you can only schedule by the minute, you can't schedule by the second.

All computers will be running Windows 7. Can powershell handle something this or do I need to get more creative?


*I was thing maybe I could use the TaskScheduler GUI to create my task which will open notepad at 08:40:15. Then open powershell or command prompt and find that task, then copy it out to the other machines. Not sure if that would work. :smith:

Hughmoris fucked around with this message at 03:49 on Aug 16, 2014

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin
I'm away from my desk but I would start with get-help new-ScheduledTask -full

I'll test it out in a bit and see if I can get something to work.

How are you going to be getting the times? Can you make a csv with the VM and time?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Dr. Arbitrary posted:

I'm away from my desk but I would start with get-help new-ScheduledTask -full

I think those were added in windows 8.

Hughmoris
Apr 21, 2007
Let's go to the abyss!

Dr. Arbitrary posted:

I'm away from my desk but I would start with get-help new-ScheduledTask -full

I'll test it out in a bit and see if I can get something to work.

How are you going to be getting the times? Can you make a csv with the VM and time?

I opened powershell, ran get-help new-ScheduledTask -full and receiver the error
code:
Get-Help: Cannot find help for topic "new-ScheduledTask
My workstation and all the VMs are running Powershell 2.0


I'm not positive what you mean about getting the times. It would run something like this:
code:
VM1      terrible_script.exe       08:05:00
VM2      terrible_script.exe       08:05:05
VM3      terrible_script.exe       08:05:10
VM4      terrible_script.exe       08:05:15
VM5      terrible_script.exe       08:05:20
VM6      terrible_script.exe       08:05:25
...
Odd question, might not make sense... When you create a task, is there a file/object created that can be copied to other machines?

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin

Ithaqua posted:

I think those were added in windows 8.

poo poo. I hate when that happens.
Maybe it can be done with .NET

I still want to make it work. This is a fun challenge.

Hughmoris
Apr 21, 2007
Let's go to the abyss!

Dr. Arbitrary posted:

poo poo. I hate when that happens.
Maybe it can be done with .NET

I still want to make it work. This is a fun challenge.

I'll have to do it without installing any further software.

And you're right, while its irritating its also a fun brain puzzler. After googling, I'm thinking maybe create the task on all the machines using the command prompt for 08:00. Then somehow export the task which appears to be an XML, edit the XML to have the time be 08:00:05, then import it. Not sure if I'm going crazy after dealing with this all day.

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin

Hughmoris posted:

I'll have to do it without installing any further software.


.Net is a prerequisite for powershell so that won't be a problem.

I think you might start with this:
http://letitknow.wordpress.com/2011/05/20/create-scheduled-task-by-using-powershell/

The key element is
$service = NewObject -ComObject("Schedule.Service")

You can then use
$Service | Get-Member
To find new properties.

This is pretty difficult territory for me so I'd just carefully look at the examples and try to work it out.

Hughmoris
Apr 21, 2007
Let's go to the abyss!

Dr. Arbitrary posted:

.Net is a prerequisite for powershell so that won't be a problem.

I think you might start with this:
http://letitknow.wordpress.com/2011/05/20/create-scheduled-task-by-using-powershell/

The key element is
$service = NewObject -ComObject("Schedule.Service")

You can then use
$Service | Get-Member
To find new properties.

This is pretty difficult territory for me so I'd just carefully look at the examples and try to work it out.

At first glance it looks like the site you listed could be a more elegant solution but I'm not too familiar with a lot of the code being used. So, I went about solving it like a caveman.

1. At my workstation, I create a local task in command-prompt:
code:
schtasks /create /tn test_task /tr notepad.exe /sc once /st 23:00
2. Now that the task is created for my local machine, I export it to a XML file:
code:
schtasks /query /xml /tn test_task > adjusted_test_task.xml
3. I edit that XML file in notepad to have a launch time of 23:00:05, then save

4. I then export that newly adjusted task file to each VM:
code:
schtasks /create /s vMachine1 /u hughmoris /p password /XML adjusted_test_task.xml /tn test_task
With this clumsy method, I'd have to do step 3 and 4 for each machine because I'd have to edit the XML file each time to increase the launch time by 5 seconds. However, that should be MUCH faster than going the the TaskScheduler GUI for each machine.


I tested it on 2 machines and it appears to work. Ugly but effective. I'm definitely ears for other solutions though.

Hughmoris fucked around with this message at 05:33 on Aug 16, 2014

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Hughmoris posted:

At first glance it looks like the site you listed could be a more elegant solution but I'm not too familiar with a lot of the code being used. So, I went about solving it like a caveman.

1. At my workstation, I create a local task in command-prompt:

2. Now that the task is created for my local machine, I export it to a XML file:

3. I edit that XML file in notepad to have a launch time of 23:00:05, then save

4. I then export that newly adjusted task file to each VM:



With this clumsy method, I'd have to do step 3 and 4 for each machine because I'd have to edit the XML file each time to increase the launch time by 5 seconds. However, that should be MUCH faster than going the the TaskScheduler GUI for each machine.


I tested it on 2 machines and it appears to work. Ugly but effective. I'm definitely ears for other solutions though.

I've taken a similar approach (the COM stuff sucks). But why not use PowerShell to set the time in the XML instead of manually editing it?

This should work:

code:
$timeOffset = 0;
$machines = @("machine1", "machine2", "etc")
$xml = [xml](get-content adjusted_test_task.xml)

$initialTime = [DateTime]::Parse($xml.Task.Triggers.TimeTrigger.StartBoundary)

foreach ($machine in $machines) {
    $outputFile = $machine + "_adjusted_test_task.xml"
    $timeOffset += 5;
    $newTime = $initialTIme.AddSeconds($timeOffset);
    $xml.Task.Triggers.TimeTrigger.StartBoundary = $newTime.ToString("s")
    set-content $outputFile $xml.InnerXml
    schtasks /create /s $machine /u hughmoris /p password /XML $outputFile /tn test_task
}

New Yorp New Yorp fucked around with this message at 17:10 on Aug 16, 2014

ConfusedUs
Feb 24, 2004

Bees?
You want fucking bees?
Here you go!
ROLL INITIATIVE!!





I've created a number of scripts to generate randomized data and files to test backups.

I'm happy with all of them except my MSSQL script. For that one, I have a .sql file that I call with powershell. It works well enough, but is there a way to talk to MSSQL and insert data into a table from powershell itself?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

ConfusedUs posted:

I've created a number of scripts to generate randomized data and files to test backups.

I'm happy with all of them except my MSSQL script. For that one, I have a .sql file that I call with powershell. It works well enough, but is there a way to talk to MSSQL and insert data into a table from powershell itself?

You can use the extensive .NET framework libraries in the System.Data namespace.

Hughmoris
Apr 21, 2007
Let's go to the abyss!

Ithaqua posted:

I've taken a similar approach (the COM stuff sucks). But why not use PowerShell to set the time in the XML instead of manually editing it?

This should work:

code:
$timeOffset = 0;
$machines = @("machine1", "machine2", "etc")
$xml = [xml](get-content adjusted_test_task.xml)

$initialTime = [DateTime]::Parse($xml.Task.Triggers.TimeTrigger.StartBoundary)

foreach ($machine in $machines) {
    $outputFile = $machine + "_adjusted_test_task.xml"
    $timeOffset += 5;
    $newTime = $initialTIme.AddSeconds($timeOffset);
    $xml.Task.Triggers.TimeTrigger.StartBoundary = $newTime.ToString("s")
    set-content $outputFile $xml.InnerXml
    schtasks /create /s $machine /u hughmoris /p password /XML $outputFile /tn test_task
}

Thanks for taking the time to do this. I don't know powershell but I think I can piece together whats happening. I'm going to try it out later tonight and I'll let you know how it works out.

Hughmoris
Apr 21, 2007
Let's go to the abyss!

Hughmoris posted:

Thanks for taking the time to do this. I don't know powershell but I think I can piece together whats happening. I'm going to try it out later tonight and I'll let you know how it works out.

Just to follow up, I attempted to create this PS script. I was unable to run the script due to being restricted by the system. After a little reading, I tried to allow it with: set-executionpolicy remotesigned. Received the error that I couldn't alter the regkey. So, there goes that. Not sure if our IT department will unlocked that for me. Either way, the higher ups want to start all this crap at 0830 Monday morning so it won't do me much good.

I do have AutoIt installed on this workstation, so I guess I'll try and figure out how to write your script in AutoIt. Unless it would be easier to write some sort of command-prompt script.

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin

Hughmoris posted:

Just to follow up, I attempted to create this PS script. I was unable to run the script due to being restricted by the system. After a little reading, I tried to allow it with: set-executionpolicy remotesigned. Received the error that I couldn't alter the regkey. So, there goes that. Not sure if our IT department will unlocked that for me. Either way, the higher ups want to start all this crap at 0830 Monday morning so it won't do me much good.

I do have AutoIt installed on this workstation, so I guess I'll try and figure out how to write your script in AutoIt. Unless it would be easier to write some sort of command-prompt script.

Copy it all into notepad, then paste it into powershell and see if it works.

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

This should work but it doesn't, and the maddening thing is I've done this before.

I'm running this dedupe finder:
http://poshcode.org/4008

I want to pipe the output to a text file; I've done this in the past, and in fact after I make this post I'm going to click the 'find other posts by this user' button to see if I figured it out here.

When I try this:
code:
.\finddupe.ps1 *.jpg >> fff.txt
I get a file called fff.txt that is zero bytes.

When I try this:
code:
.\finddupe.ps1 *.jpg | Out-File fff.txt
I get a file called fff.txt that is 2 bytes but still empty.

When I try this:
code:
.\finddupe.ps1 *.jpg | tee fff.txt
I don't get anything, the file doesn't even get created. The output of the script above is using Write-Host, which >> should be hijacking based on everything I read. e.g., the summary output:
code:
write-host "Number of Files checked: $($files.count)."
write-host "Number of duplicate files: $m."
Write-host "$($hashfiles) files hashed."
Write-Host "$($hashsize) bytes hashed."
write-host "$dupebytes duplicates bytes."
What am I missing?

Fenrisulfr
Oct 14, 2012

Scaramouche posted:

I don't get anything, the file doesn't even get created. The output of the script above is using Write-Host, which >> should be hijacking based on everything I read. e.g., the summary output:
code:
write-host "Number of Files checked: $($files.count)."
write-host "Number of duplicate files: $m."
Write-host "$($hashfiles) files hashed."
Write-Host "$($hashsize) bytes hashed."
write-host "$dupebytes duplicates bytes."
What am I missing?

Those Write-Hosts need to be Write-Outputs to stream them to an output like that. Write-Host specifically writes to the console, which is why your redirects aren't working. You can also use Start-Transcript and Stop-Transcript, which will work with Write-Hosts since it'll grab anything written to the console.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Change write-host to write-output.

CLAM DOWN
Feb 13, 2007




Reminder that Start/Stop-Transcript does not work in the ISE.

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Hmm, thanks guys. The weird thing is, the date-time stamp on the script is from when I did this last, and I was going over 500,000 files, so I must have figured out a way to get that data without changing the actual script. After doing a bit of reading it makes sense that this won't work since write-host is meant for screen only. I guess my memory was playing tricks on me, which is probably the worst thing to rely on. You probably spend more time trying to do something "because I remembered it was easy last time" than you do trying it the right way.

Dren
Jan 5, 2001

Pillbug
I have never used powershell before and I would like to unzip a file.

What is a good way to do that?

I found this function:
code:
function Expand-ZIPFile($file, $destination)
{
    $shell = new-object -com shell.application
    $zip = $shell.NameSpace($file)
    foreach($item in $zip.items())
    {
        $shell.Namespace($destination).copyhere($item)
    }
}
but it craps and dies w/
code:
PS C:\Users\vagrant\src> Expand-ZIPFile -File ".\mingw-get-0.6.2-mingw32-beta-20131004-1-bin.zip" -Destination "."
You cannot call a method on a null-valued expression.
At C:\Users\vagrant\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:5 char:32
+     foreach($item in $zip.items <<<< ())
    + CategoryInfo          : InvalidOperation: (items:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
I'm on Windows Server 2008 r2.

Is my powershell not the right version or something? How would I even know?

edit: also I ran a command with a lot of output and it was taking FOREVER to print to the screen. Is this a general problem or is it because I'm accessing the machine over rdp from linux?

Dren fucked around with this message at 23:10 on Sep 8, 2014

CLAM DOWN
Feb 13, 2007




Do you have the option of using the 7zip command line utility? I think it works way better and is way easier, I also recall some restrictions with using the built-in method like you are, like it doesn't work on zip files with subfolders, etc.

Dren
Jan 5, 2001

Pillbug

CLAM DOWN posted:

Do you have the option of using the 7zip command line utility? I think it works way better and is way easier, I also recall some restrictions with using the built-in method like you are, like it doesn't work on zip files with subfolders, etc.

Yeah I could do that. I was going to try to avoid it to minimize dependencies but if the thing to do is 7zip cmdline utility I'll do that.

I looked at the OP a bit and now I see that $shell in that script is holding a com object. I saw that I can do
code:
$shell | get-member
To see the members of the com object. Is there any way I can get more detailed help about that com object and it's members? What about a list of all the com objects that are available?

edit: Is there a convention for where to put stuff like 7zip? I could toss it in C:\7zip and throw that in the path I guess.

Dren fucked around with this message at 23:25 on Sep 8, 2014

Spazz
Nov 17, 2005

Any suggestions on a book for someone who has PS experience but wants to round out their knowledge? I've been writing scripts for about 9~ months now, with past Python experience, but I know I'm missing some stuff.

I was looking at Windows PowerShell Cookbook: The Complete Guide to Scripting Microsoft's Command Shell, but I'm open to other suggestions. Work is reimbursing me so cost isn't an issue as long as it isn't ridiculous.

Adbot
ADBOT LOVES YOU

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin

Spazz posted:

Any suggestions on a book for someone who has PS experience but wants to round out their knowledge? I've been writing scripts for about 9~ months now, with past Python experience, but I know I'm missing some stuff.

I was looking at Windows PowerShell Cookbook: The Complete Guide to Scripting Microsoft's Command Shell, but I'm open to other suggestions. Work is reimbursing me so cost isn't an issue as long as it isn't ridiculous.

I think there's a toolmaking in a month of lunches book that might be up your alley.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply