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
BaseballPCHiker
Jan 16, 2006

Hadlock posted:

5 is supposed to support linux-style package management system(s), like apt-get and yum, replacing the need for stuff like ninite.

Find-Package -Name AdobeReader | Install-Package
Find-Package -Name WinRAR, Skype, Opera | Install-Package

It also supports formal programming classes in addition to functions, etc. Also deeper DSC support, and tighter Hyper-V integration.

Basically if you manage more than 20 servers and have to deploy code to them on a regular basis, it's very helpful. You can define your own software repositories of course. Not as useful if you're a desktop user.

And yeah, syntax highlighting in the ISE :dance:

There are more, but those are the most relevant to my world right now.

Do you know if Chocolately is changing to this or going away? I use it now and it works great for some of our quick lite touch deployments, we just install Chocolately and then give it the list of apps to install.

Adbot
ADBOT LOVES YOU

Sefal
Nov 8, 2011
Fun Shoe
I'm familiarizing myself more and more with powershell.
But uhm how do i create a log? I'm sending the list of inactive users accounts (who are going to be deleted) to the company mail
But that's the lazy way.
I wanna be able to say. This is what happened. This is what is going to happen in a log file and send that as an attachment.
I want to put in.

If $users are deleted. write-output or something like that.
I wanna be able to list the users that are deleted and their homedrive. I wanna know how i can do that. so i can know how to log further powershell scripts i'm making
Can you guys help?


code:
Add-PSSnapin Quest.ActiveRoles.ADManagement
$Destinationdir = "F:\Destination test Sefal"
$Today = get-date
$OU = "company.nl/Accounts/Disabled Accounts"
$Path = "F:\test\InactiveUserAccounts.csv"


$users= Get-QADUser -InactiveFor 90 -Disabled -SizeLimit 0 -searchroot $OU |  
 where {$_.WhenChanged.Adddays(90) -lt $Today } | 
 Sort WhenChanged |
 Select-Object DisplayName |
 Export-csv -path $Path
 #Remove-qadobject -identity $users 


ForEach ($user in $users) 
{ write-host -foregroundcolor red $user.homedirectory 
      
           
            #Copy Items Into Destiation
            copy-Item $user.homedirectory $DestinationDir -recurse -Force
            #remove-item $user.HomeDirectory
 }
 

$SmtpServer = "smtp.company.nl"
$From = "our Domain Controller <noreply-dcXX@company.nl>"
$To = "Sefal@company.nl"
#,"groupmail@company.nl";
#$To ="groupmail@ecomapny.nl";
$Subject = "List of deleted ad users "
$Body ="enclosed you will find a list of the deleted users "

Send-mailmessage -from $From -to $To -subject $Subject -body $Body -Attachments $path -smtpServer $SmtpServer

BaseballPCHiker
Jan 16, 2006

There are two things that come to mind. The first is that you should be able to use the Start-Transcript cmdlet to keep a log of any thing done by powershell and have it write to a text file. More info here:
https://technet.microsoft.com/en-us/magazine/ff687007.aspx
I use it as part of my Powershell profile so that it loads whenever I start it up, it definitely helps to be able to go back and look and see what I was trying to do.

code:
# Automate PowerShell Transcription
# Create a filename based on a time stamp.
$Filename = ((Get-date).Month).ToString()+"-"+`
    ((Get-date).Day).ToString()+"-"+`
    ((Get-date).Year).ToString()+"-"+`
    ((Get-date).Hour).ToString()+"-"+`
    ((Get-date).Minute).ToString()+"-"+`
    ((Get-date).Second).ToString()+".txt"
# Set the storage path.
$Path = "C:\Scripts\Logs"
# Turn on PowerShell transcripting. 
Start-Transcript -Path "$Path\$Filename"
The other thing is that you are already piping out the disabled user accounts to a CSV file. Can't you just send that when you want to?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

BaseballPCHiker posted:

There are two things that come to mind. The first is that you should be able to use the Start-Transcript cmdlet to keep a log of any thing done by powershell and have it write to a text file. More info here:
https://technet.microsoft.com/en-us/magazine/ff687007.aspx
I use it as part of my Powershell profile so that it loads whenever I start it up, it definitely helps to be able to go back and look and see what I was trying to do.

code:
# Automate PowerShell Transcription
# Create a filename based on a time stamp.
$Filename = ((Get-date).Month).ToString()+"-"+`
    ((Get-date).Day).ToString()+"-"+`
    ((Get-date).Year).ToString()+"-"+`
    ((Get-date).Hour).ToString()+"-"+`
    ((Get-date).Minute).ToString()+"-"+`
    ((Get-date).Second).ToString()+".txt"
# Set the storage path.
$Path = "C:\Scripts\Logs"
# Turn on PowerShell transcripting. 
Start-Transcript -Path "$Path\$Filename"
The other thing is that you are already piping out the disabled user accounts to a CSV file. Can't you just send that when you want to?

:gonk:

Your timestamp is faulty. If you do alpha sorting, 7 comes up as greater than 10. Replace that whole mess with this:
get-date -Format MM-dd-yyyy-hh-mm-ss

I think that's also susceptible to repeating timestamps, potentially. You get the current date/time on every call to get-date, so if you run it on the cusp of a minute/hour/day/month/etc change, you could end up with this:

Get-Date = 12:59:00 -> get minute = 59
Get-Date = 12:59:01 -> get second = 01
Full timestamp:
12:59.01

then, later:
Get-Date = 12:59:59 -> get minute = 59
Get-Date = 13:00:01 -> get second = 01
Full timestamp:
12.59.01

New Yorp New Yorp fucked around with this message at 15:12 on Jul 23, 2015

BaseballPCHiker
Jan 16, 2006

Ithaqua posted:

:gonk:

Your timestamp is faulty. If you do alpha sorting, 7 comes up as greater than 10. Replace that whole mess with this:
get-date -Format MM-dd-yyyy-hh-mm-ss


Wow much better, thank you! I did that and changed this part to:
code:
# Turn on PowerShell transcripting. 
Start-Transcript -Path "$Path\$Filename.txt"
And it's working great. Just goes to show how much I have to learn about Powershell. The next two projects I want to force myself to learn are bulk AD user account creation from CSV and just general Powershell Exchange management.

Briantist
Dec 5, 2003

The Professor does not approve of your post.
Lipstick Apathy

Dr. Arbitrary posted:

I'm working on a project to verify firewall settings.

The manual strategy is to remote to a host, use telnet to try and connect to various targets and ports and record the results.

Manual sucks.

I tried using
$Connection = New-Object.System.Net.Sockets.TcpClient
$Connection.BeginConnect("Host",12345,$null,$null)
Then check the status with $Connection
Then closing with
$Connection.close()

Does this seem like a good place to start with this or am I running the risk of screwing stuff up?

I know this is from last page, but I have this function I use as part of a larger project. It's not really written in my style so either this was a long time ago or I stole half the code from somewhere else:

code:
Function Test-TCPPort
{
    [CmdletBinding()]
    Param(
        [ValidateNotNullOrEmpty()]
        [string] $EndPoint = $(throw "Please specify an EndPoint (Host or IP Address)"),
        [string] $Port = $(throw "Please specify a Port"),  
        [int] $TimeOut = 1000
    )
       
        $IP = [System.Net.Dns]::GetHostAddresses($EndPoint)
        $Address = [System.Net.IPAddress]::Parse($IP)
        $Socket = New-Object System.Net.Sockets.TCPClient
        $Connect = $Socket.BeginConnect($Address,$Port,$null,$null)
        $Wait = $Connect.AsyncWaitHandle.WaitOne($TimeOut,$false)                      
        if(!$Wait)
        {
                $Socket.Close()
                return $false
        }
        else
        {
            $rv = $true
            try {
                $Socket.EndConnect($Connect)
            } catch {
                $rv = $false
            } finally {
                $Socket.Close()
            }
            return $rv
        }
}

Venusy
Feb 21, 2007

Sefal posted:

I'm familiarizing myself more and more with powershell.
But uhm how do i create a log? I'm sending the list of inactive users accounts (who are going to be deleted) to the company mail
But that's the lazy way.
I wanna be able to say. This is what happened. This is what is going to happen in a log file and send that as an attachment.
I want to put in.

If $users are deleted. write-output or something like that.
I wanna be able to list the users that are deleted and their homedrive. I wanna know how i can do that. so i can know how to log further powershell scripts i'm making
Can you guys help?

If you want a .txt version rather than the CSV, then you can just put $user | Out-File .\log.txt -Append in the foreach block.

Or if you want a timestamp in there:
"$(Get-Date): Deleted user $user" | Out-File .\log.txt

Sefal
Nov 8, 2011
Fun Shoe
Thank you. the transcript command was what I needed

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Sefal posted:

Thank you. the transcript command was what I needed

Note that transcripts don't work when you're running the script in the ISE. Or at least they didn't last time I tried to use it. It made it essentially worthless.

Sefal
Nov 8, 2011
Fun Shoe

Ithaqua posted:

Note that transcripts don't work when you're running the script in the ISE. Or at least they didn't last time I tried to use it. It made it essentially worthless.

Oh yeah i got that error the 1st time. "This host does not support transcription" but after some quick goolging, found it didnt work in the ISE. It supposedly does work in the ISE of powershell v5

Briantist
Dec 5, 2003

The Professor does not approve of your post.
Lipstick Apathy

Sefal posted:

Oh yeah i got that error the 1st time. "This host does not support transcription" but after some quick goolging, found it didnt work in the ISE. It supposedly does work in the ISE of powershell v5

Transcript also won't capture any output from shell commands or external .exe files. Not sure if that changed in 5 or not.

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin
Anyone have recommendations for intermediate level Powershell books. I've already read month of lunches (although I might order toolmaking in a month of lunches).

Hadlock
Nov 9, 2004

BaseballPCHiker posted:

Do you know if Chocolately is changing to this or going away? I use it now and it works great for some of our quick lite touch deployments, we just install Chocolately and then give it the list of apps to install.

I only played around with it when it was first announced last fall, and never actually got it to work. From what I understand, the system ps5 is using is engineered so that it will work with multiple package suppliers and is modeled after chocolatey and you can set up chocolatey as your primary package supplier... Or whatever. I haven't played around with it yet.

Venusy
Feb 21, 2007

Ithaqua posted:

Note that transcripts don't work when you're running the script in the ISE. Or at least they didn't last time I tried to use it. It made it essentially worthless.
This may have been fixed with the regular Start-Transcript command since, but if not, providing you've got either PowerShell v5 or the November update for PowerShell v4:


EDIT: Also, while trying to find the KB value of the update rollup, I found this page, which is a pretty neat list of all the stuff they've added in v5.

Venusy fucked around with this message at 21:37 on Jul 24, 2015

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin
I have an idea for a script but I'm not sure if it's crazy or already been done.

The basic idea is that it validates a list of requirements.

Easy enough to start, a bunch of if/else statements contingent on wmi queries etc.

But what if I made a script that let you specify a series of checks and then exported that as an XML object, and then turned the validator script into a function that accepted the XML file as a parameter.

You could have a standardized thing for prerequisites that would work the same way every time.

Or is this reinventing the wheel or crazy or dumb?

12 rats tied together
Sep 7, 2006

I think that's basically DSC, or Chef's windows plugin, or Ansible running over wmic. If I'm understanding you correctly, anyway.

Hadlock
Nov 9, 2004

There's a product called Guardrail that I'm getting ready to roll out at my company next month that basically does that. It's cross-platform but the windows side of things runs powershell scripts and compares the output to what's expected and let you know what's gone awry. It's compatible with Chef, Puppet etc but is better designed to get your infrastructure under control so that you can some day propose going full chef/puppet and actually expect it to be completed reasonably on time.

You should code it anyways, the company that makes Guardrail just got a second, ~$10 million round of venture capital funding. Apparently there's a large market for that kind of thing.

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin

Hadlock posted:

You should code it anyways

I think I will. Worst case, it sucks and maybe I learn something.

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin
I know that Win32_Product is dangerous. Are there any others to look out for or they all mostly safe?

Briantist
Dec 5, 2003

The Professor does not approve of your post.
Lipstick Apathy

Dr. Arbitrary posted:

I know that Win32_Product is dangerous. Are there any others to look out for or they all mostly safe?
That's a good question; I haven't heard of any others.

Tony Montana
Aug 6, 2005

by FactsAreUseless

Dr. Arbitrary posted:

I have an idea for a script but I'm not sure if it's crazy or already been done.

The basic idea is that it validates a list of requirements.

Easy enough to start, a bunch of if/else statements contingent on wmi queries etc.

But what if I made a script that let you specify a series of checks and then exported that as an XML object, and then turned the validator script into a function that accepted the XML file as a parameter.

You could have a standardized thing for prerequisites that would work the same way every time.

Or is this reinventing the wheel or crazy or dumb?

Doesn't SCCM do exactly this?

I guess I'd query WMI.. the comparing it to what a value should be shouldn't be too hard.

Your own custom script looking at exactly what you need and producing a sexy report is going to be superior to wrestling out of a tool like SCCM anyway. As long as you put the time into your reporting and don't point to jumbled CSVs like lots of lazy scripters do (I had to understand it, so why can't you?)

It's not job security in the sense you're producing custom stuff no-one else can support, it's job security in that's is a cool accomplishment to talk about. You can answer the now ubiquitous 'how is your Powershell?' interview question with examples like this :)

CLAM DOWN
Feb 13, 2007




Oh my god I totally just learned you can do this

code:
#requires -version 4.0
#requires –runasadministrator
:stare:

vanity slug
Jul 20, 2010

CLAM DOWN posted:

Oh my god I totally just learned you can do this

code:
#requires -version 4.0
#requires –runasadministrator
:stare:

You can also do this for modules :) No more complicated functions to check if the ActiveDirectory module is active, just
code:
#Requires -Modules ActiveDirectory
It's the best thing.

CLAM DOWN
Feb 13, 2007




Jeoh posted:

You can also do this for modules :) No more complicated functions to check if the ActiveDirectory module is active, just
code:
#Requires -Modules ActiveDirectory
It's the best thing.

omg

Doug
Feb 27, 2006

This station is
non-operational.
I'm working on a script to automate password resets/account lockouts. The way it works right now is:

-Cell phone numbers stored in AD for each user
-User sends text to email address
-Script looks for emails in the service box

At first I was just taking all information before the @ in the email address as the phone number but then I found out there could be some variance in that piece because some providers may or may not include + and 1 in the phone number. Now I'm trying to manipulate the string such that I take the first 10 digits before the @ as phone number. That way any leading information that may or may not be included won't be part of the look up. It seems I've messed something up in the string manipulation though because my tests are setting the variable as xxxxxxxxxx@x . So it's getting the phone number and disregarding the extraneous information but for some reason now it's pulling the @ and the first character after the @ as part of the string. What am I missing? Here's the snippet for the string manipulation:

$Phone = $item.From.address.substring(($Phone.IndexOf("@")-10), $Phone.IndexOf("@"))

12 rats tied together
Sep 7, 2006

Given the input of "2223334444@provider.net", if you do a substring() for @-10,@, yeah you will pull just the phone number. If you try "+12223334444@provider.net", you'll get the number, the @ symbol, and the character after it.

The reason for this is that the arguments to Substring() are "where to start" and "how far to go". It's not array index selection, so when you call what is essentially Substring(0,10) you say "start at the first character and go forwards 10 characters". When you call Substring(2,12) (as is the case when your input contains +1, because @ is 2 indexes further into the string), you say "start at the second and go forwards 12 characters".

You may need to do some more intelligent handling -- for example you could try doing a $string.Replace() to trim the string to what you want. You can match "at the beginning of a string" with the ^ symbol in regex (not really sure on the specifics of this in powershell though), and then it would be trivial to trim "everything after, and including, the first @-symbol". I would prefer this to Substring or index manipulation personally but I guess it's a style choice at that point.

Additionally, you could replace your Substring() method with index selection, for example:
code:
$string[($string.IndexOf("@")-10)..$($string.IndexOf("@")-1)]
But you would still want to dynamically determine the start of the string instead of just passing IndexOf("@")-10.

12 rats tied together fucked around with this message at 15:33 on Aug 3, 2015

Doug
Feb 27, 2006

This station is
non-operational.

Reiz posted:

Given the input of "2223334444@provider.net", if you do a substring() for @-10,@, yeah you will pull just the phone number. If you try "+12223334444@provider.net", you'll get the number, the @ symbol, and the character after it.

The reason for this is that the arguments to Substring() are "where to start" and "how far to go". It's not array index selection, so when you call what is essentially Substring(0,10) you say "start at the first character and go forwards 10 characters". When you call Substring(2,12) (as is the case when your input contains +1, because @ is 2 indexes further into the string), you say "start at the second and go forwards 12 characters".

You may need to do some more intelligent handling -- for example you could try doing a $string.Replace() to trim the string to what you want. You can match "at the beginning of a string" with the $^ symbol in regex (not really sure on the specifics of this in powershell though), and then it would be trivial to trim "everything after, and including, the first @-symbol". I would prefer this to Substring or index manipulation personally but I guess it's a style choice at that point.

Additionally, you could replace your Substring() method with index selection, for example:
code:
$string[($string.IndexOf("@")-10)..$($string.IndexOf("@")-1)]
But you would still want to dynamically determine the start of the string instead of just passing IndexOf("@")-10.

Hm, well that makes sense why my solution isn't working. I'm fairly new to powershell so I'm trying to work out in your response what I can use to solve the problem. Index selection seems to make the most sense to me, so I tried:

code:
$Phone = $Phone[($Phone.IndexOf("@")-10)..$($Phone.IndexOf("@")-1)]
That seems to have set the string to all of the correct characters but with a new line between each character. I don't think I understand well enough what's happening to figure out how to fix it.

12 rats tied together
Sep 7, 2006

Oh, yeah, sorry about that. There's definitely a way better way to do this, but, quick fix:

code:
$string[($string.IndexOf("@")-10)..$($string.IndexOf("@")-1)] | % { $newstring += "$_" }
Select your indexes, pass them into a ForEach-Object loop and add the current index to the string $newstring, or whatever. $newstring will be the values of each index you grab.

But, to zoom out a second here, I'd probably do something like:

code:
$Phone = Get-Whatever

if ($Phone.StartsWith("+") {
    $TrimmedPhone = ($Phone | select-string -Pattern '(?<=\+1).+(?=\@)').Matches.Value 
}

else {
    $TrimmedPhone = ($Phone.Split("@")[0]
}
My regular expressions arent the best, but the pattern is basically "Match everything between, but not including, "+1" and "@". When you do a select-string or -match operator in powershell it usually automatically creates a $Matches dictionary with the results of your operation. I believe in this dictionary the "Key" is the match number (in sequence, because you can match more than one thing), and the "Value" is the result of your match. So, when we do ".Matches.Value" it will return all of the matched content from all of the matches. IIRC, you can limit this by doing ".Matches[0].Value" or similar, but since we're only matching one thing that should work fine.

The second part just takes your phone number, splits it on the @ sign, and returns the first half. In either case you should be left with just the phone number.

edit: Actually, it would probably better to just do this:
code:
$Phone = ($Phone.Split("@"))[0]
if ($Phone.StartsWith("+1") { $Phone = $Phone.TrimStart("+1") }

12 rats tied together fucked around with this message at 16:22 on Aug 3, 2015

Doug
Feb 27, 2006

This station is
non-operational.

Reiz posted:

edit: Actually, it would probably better to just do this:
code:
$Phone = ($Phone.Split("@"))[0]
if ($Phone.StartsWith("+1") { $Phone = $Phone.TrimStart("+1") }

Two notes:

First, the quick fix is doing something weird. If I leave off the pipe into ForEach-Object loop, I get the correct values for the 10 digit phone number with new line characters. If I add in the FE-O loop, it concatenates the digits, but for some reason the string now has a 1 at the beginning. I'm really struggling to understand how that "1" character gets added.

So instead of trying to bang my head against that for much longer, I tried the second approach. I also added in a line about "if $phone starts with 1 trim 1" just in case there are providers that send the 1 without the plus. It looks like that's doing the job. Thanks!

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Reiz posted:

Given the input of "2223334444@provider.net", if you do a substring() for @-10,@, yeah you will pull just the phone number. If you try "+12223334444@provider.net", you'll get the number, the @ symbol, and the character after it.

The reason for this is that the arguments to Substring() are "where to start" and "how far to go". It's not array index selection, so when you call what is essentially Substring(0,10) you say "start at the first character and go forwards 10 characters". When you call Substring(2,12) (as is the case when your input contains +1, because @ is 2 indexes further into the string), you say "start at the second and go forwards 12 characters".

You may need to do some more intelligent handling -- for example you could try doing a $string.Replace() to trim the string to what you want. You can match "at the beginning of a string" with the ^ symbol in regex (not really sure on the specifics of this in powershell though), and then it would be trivial to trim "everything after, and including, the first @-symbol". I would prefer this to Substring or index manipulation personally but I guess it's a style choice at that point.

Additionally, you could replace your Substring() method with index selection, for example:
code:
$string[($string.IndexOf("@")-10)..$($string.IndexOf("@")-1)]
But you would still want to dynamically determine the start of the string instead of just passing IndexOf("@")-10.

This is easy with a regex unless I missed something:

code:
$regex = '\+{0,1}([0-9]{10,11})@(.*)'
'+12225556666@foo.net' -match $regex
'2225556666@foo.net' -match $regex
'12225556666@foo.net' -match $regex
$Matches[0] is the full match
$Matches[1] is the phone number
$Matches[2] is the domain

New Yorp New Yorp fucked around with this message at 17:59 on Aug 3, 2015

Briantist
Dec 5, 2003

The Professor does not approve of your post.
Lipstick Apathy

CLAM DOWN posted:

Oh my god I totally just learned you can do this

code:
#requires -version 4.0
#requires –runasadministrator
:stare:
The runasadministator one was added in 4.0.

Jeoh posted:

You can also do this for modules :) No more complicated functions to check if the ActiveDirectory module is active, just
code:
#Requires -Modules ActiveDirectory
code:
#Requires -Modules ActiveDirectory
It's the best thing.
Not that it isn't great (I use it too), but the code wasn't complicated before:

code:
Import-Module ActiveDirectory -ErrorAction Stop
That effectively does the same thing.

Hadlock
Nov 9, 2004

That moment when you realize the script you just spent half an hour debugging, is not working because you're using if($a = $b){stuff} instead of if($a -eq $b){stuff}

:smithicide:

Tony Montana
Aug 6, 2005

by FactsAreUseless
It would have worked in VB :)

Briantist
Dec 5, 2003

The Professor does not approve of your post.
Lipstick Apathy

Hadlock posted:

That moment when you realize the script you just spent half an hour debugging, is not working because you're using if($a = $b){stuff} instead of if($a -eq $b){stuff}

:smithicide:
This is the kind of thing that Set-StrictMode should catch but doesn't. :(

Swink
Apr 18, 2006
Left Side <--- Many Whelps
I've wasted hours on that same thing.

Briantist
Dec 5, 2003

The Professor does not approve of your post.
Lipstick Apathy
http://blogs.msdn.com/b/powershell/archive/2015/08/06/windows-management-framework-wmf-5-0-roadmap.aspx

The Windows Management Framework 5 Roadmap has been posted!

They're doing an interesting thing here, releasing a "production preview" version sometime this month, and then the RTM version in Q4.

Production Preview sounds like some beta poo poo but it's "fully supported" and has no experimental features.

I'm happy to be able to get 5.0 on production machines without waiting for Server 2016 to come out.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
This is an embarrassing post to make but I'm in a serious time hole and don't have time to think.

If I've got a file called 0072.png, how can I make 71 copies of it (0001.png through 0071)?

Zaepho
Oct 31, 2013

Newf posted:

This is an embarrassing post to make but I'm in a serious time hole and don't have time to think.

If I've got a file called 0072.png, how can I make 71 copies of it (0001.png through 0071)?
code:
foreach ($i in (1..71)) {
   $NewFilename = "{0:D4}.png" -f $i
    Copy-item 0072.png $Newfilename
}
Test before use. I slapped it together without any testing/trial/etc. YMMV

Edit: OK I kinda tested and fixed an issue. Should pretty much work. Try a whatif first to make sure.

Zaepho fucked around with this message at 04:28 on Aug 8, 2015

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin

Newf posted:

This is an embarrassing post to make but I'm in a serious time hole and don't have time to think.

If I've got a file called 0072.png, how can I make 71 copies of it (0001.png through 0071)?

code:
for($i=1
    $i -le 9
    $i++){
    Write-Host ("00"+"$i")
    copy-item 0072.png ("000"+$i+".png")
    }
for($i=10
    $i -le 71
    $i++){
    Write-Host ("00"+"$i")
    copy-item 0072.png ("00"+$i+".png")
    }
Edit
poo poo, not only was I beaten by about six minutes, I wrote crappier code.

Dr. Arbitrary fucked around with this message at 04:37 on Aug 8, 2015

Adbot
ADBOT LOVES YOU

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Thanks both. Worked like a charm.

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