"...and centered the taskbar and Start button so you always know where home is.”
https://www.microsoft.com/en-us/windows/event
​
​
Ironically this means that the start button can be in different places in contrast to always being left bottom corner for the last couple of decades.
The best way to learn anything depends on your learning style. Some people learn better by reading, some by watching videos, and some by doing. It's important to know how you learn effectively.
That said, my recommendation is to find a routine task you do regularly and figure out how to do it automatically with PowerShell. Do you archive old report files to a specific directory structure? Learn about Copy-Item
. Do you manage Exchange, SCCM, O365, anything like that? They all have automation support with PowerShell. There are even community modules that support a lot of third-party products - for example, the JiraPS project allows you to manage JIRA items with PowerShell, including creating new issues, commenting on existing ones, and closing them out.
If you prefer reading, the book <u>Learn PowerShell in a Month of Lunches</u> is often recommended - but it's very important that you actually follow along with the exercises in the book. Type them and run them on a live computer whenever possible.
If you prefer videos, I suggest the Microsoft Virtual Academy series on PowerShell. These are a bit long, but they do a great job of teaching you both concepts and practical knowledge.
Hope that helps!
Honestly, I'd go with Windows Powershell Best Practices instead. PSIAMOL is nice, but this one focuses more heavily on ensuring you not only get the syntax, but the proper script structure, code re-usability, high performance, and just a ton of other stuff.
PSIAMOL Teaches you how to use PowerShell. WPBP teaches you how to be good at PowerShell.
Once that's done, it wouldn't hurt to check out Code Complete which had such an impact I ended up re-writing several of my larger scripts after reading it...
Powershell in a month of lunches is apparently quite good, that will cover Powershell from the basics to relatively advanced concepts, although I don't recall it covers AD.
Once you have a grasp of PowerShell, the AD modules are not much trouble to learn at all, MCSA should at least cover some of that.
Also - Take a look under the "resources" tab on the right of this sub.
I have an automated task using WinSCP. Rather than install the app on the server we're running from, I pull in the executable and one DLL file needed for the process (WinSCP.exe and WinSCPNet.dll).
Here are their documents on scripting: https://winscp.net/eng/docs/scripting
Visual Studio Code is what is being suggested most. The default PS ISE is pretty limited out of the box, and Microsoft announced that it won't be developed anymore, and all new work is happening in vscode.
https://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples
http://effbot.org/pyfaq/why-are-floating-point-calculations-so-inaccurate.htm
Floating point arithmetic is an approximation.
If you’re looking for resources that may be helpful, have you tried the “Learn PowerShell in a month of lunches” series by Don Jones? https://www.amazon.com/dp/1617294160/ref=cm_sw_r_cp_api_i_fJafCb1K1VSKQ
Also, Microsoft Virtual Academy has a good training course with Jeffrey Snover (https://mva.microsoft.com/en-US/training-courses/getting-started-with-microsoft-powershell-8276)
They’ve been a major help to me and I had no experience coding prior to them.
> 1) Object oriented pipes
In my experience, this one separates the folks who thoughtfully consider their toolset from the ones that are just rabidly anti-MS or resistant to all change.
I'm longing for the day that Pash is complete enough for Real Work on Linux.
I found a tutorial when i googled "i hate powershell". It gave me a new perspective on it and now i start to even like using it.
Edit: Found it!
I'll probably invoke a lot of wrath here, but oh well.
Let me start by saying that I love PowerShell [Core]. I started my career in IT operations for a large enterprise (12k+ workstations) and did a ton of PowerShell scripting.
Desktop techs wanted GUIs, though, so I started down this same path of creating them in PowerShell (with WPF as you are).
Eventually, I hit all the technical and maintainability roadblocks that you'll eventually discover. Ultimately, I decided to learn C#, and eventually learned the MVVM pattern.
The learning curve wasn't terrible. And afterward, development was infinitely faster, better, and more enjoyable. After getting first WPF app using C#, I wished I could take back all the hundreds of hours I wasted on developing in PowerShell.
And I'm not saying throw out your PS scripts and rewrite the logic in C#. You can add the PowerShell SDK NuGet package and run your scripts directly from your C# app. Or you can start an external PS process to run the script.
I'm just advocating that the "wrapper" app be done in C# WPF. The development, debugging, and tooling benefits will outweigh the learning effort very quickly.
This. OP sounds like he's not using version control / is concerned about saving changes if untested.
Go to https://git-scm.com and the r/ git subreddit has good learning resources. If you're working alone it's a lot easier to learn committing and undoing mistakes. When you learn to branch you can make more complex changes in dev and easily switch back to your master branch with the known-good prod code.
Here's a tip from the folks at Chocolatey:
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
First bit changes execution policy to a script will run. Second bit forces TLS 1.2. Third bit (the iex, which is short for Invoke-Expression) downloads the installer script using .NET code and runs it.
It sure is free! I haven't opened ISE in a year even going so far as to install it on most of our Dev/Staging servers.
- Visual Studio Code
- PowerShell Extension for Visual Studio Code
> I like to learn new languages
Then learn PowerShell. There's a lot to love about the learning experience. I may be a bit bias towards it, but it was seriously one of the most fun languages to learn for me. Especially if you are already comfortable on the command line, which is likely if you're mainly into Linux :)
The rest is less important, because at the end of the day the worst thing you could end up with a nice shell to use at work. That being said...
> Now, I would like to pull some data from the web and Outlook into Excel and generate some reports etc
PowerShell is an easy choice for Outlook and Excel. You can use the same COM objects you do in VB, or use a community module. Most community modules are open source with very easy to integrate licenses. ImportExcel uses Apache for instance.
Web scraping is awkward compared to other languages, but the HtmlAgilityPack helps a lot with that. If you are used to using xpath for scraping, you'll want to use HAP. If you don't need xpath look into Invoke-WebRequest
. It's a default cmdlet and get's the job done.
For now, most of the settings are only accessible in a json file - here's the md about them:
https://github.com/microsoft/terminal/blob/master/doc/cascadia/SettingsSchema.md
"-contains" and "-notcontains" don't do what you're thinking they do. Check out http://technet.microsoft.com/en-us/library/dd315321.aspx for more information. Try this instead:
{if ($i.name -notlike "*`$")
I say WPF. It's the newer, better supported technology. It is also cleaner to implement. You have nice, structured XaML defining the UI layout and, actually, about the same amount of code as WinForms defining the actions. You can do a LOT with WPF. I even made combobox, button, and progress bar templates that are styled to look like UWP. You can embed SVG images as well. In fact, Inkscape has the option to Save-As XaML directly.
​
That said, I also have Visual Studio Enterprise, which has a built in WPF GUI Designer. I would recommend building your XaML that way. If you don't have VS, the Open Source project SharpDevelop has a WPF GUI Designer that mimics the on in Visual Studio.
​
If you want the really simple solution, look into Show-Command
As a side-note, you might want to try visual-studio-code as an editor - same developer maintains ISE and the extension in VSCode. I've been fulltime in VSCode since January and love it.
>Not sure why anyone is still using ISE for anything PowerShell related.
I get it, it's the new hotness, and yes I do use it, when needed and have since day one. Well, I use the release and the preview, just because.
I've been using Powershell since before it was called PowerShell (aka Monad) and the original ISE had features they pulled, in the later versions and the new versions, has featured the legacy did not. The features pull they did on legacy really angered me.
There is a lot about VSCode, that sends me into fits of anger daily.
So:85% of the time - ISE daily work (especially on the various customer sites I support)
Everyone has their choice and one is not any better than the other depending on a user-specific use case/needs/requirements. ALl my environments/tools are heavily customized for the tasks needed.
No. They've stated their working on a scheme that could possibly support this but right now it can't because it is considered insecure.
https://github.com/microsoft/terminal/issues/632#issuecomment-491033558
First, this is not something that either cmd.exe or BASH (or whatever shell you like) is doing. TAIL is a program. It's like saying that BASH can't run sfc.exe.
Second, PowerShell can "tail" a file (kinda):
Get-Content c:\logfile.log -wait
This is basically the equivalent of "tail -f".
Now granted, it's not as flexible or robust, but still pretty awesome nonetheless. And if you want to have some real TAIL style functionality in PowerShell, install BareTail.exe, and run it from PowerShell (or one of these other Win32 TAIL implementations: http://serverfault.com/questions/7263/convenient-windows-equivalent-to-tail-f-logfile).
EDIT: To be fair, the -wait parameter is not documented in the Get-Content help files. But you can find it with this:
Get-Command Get-Content | fl
Which doesn't rely on documentation, but on reflection over the cmdlet code.
I once had to delete 19 million files from a single directory. Any attempts to list the directory resulted in all the system's memory to be consumed and the system would effectively lock up. It was amazing.
I used voidtools everything (https://www.voidtools.com/) to filter and export a massive CSV list of all the files. Then powershell to parse the CSV and delete the files one at a time. It took a couple days but it damn well worked.
I use WinSCP quite often when dealing with GUI. It's only for SFTP tho. For FTPS I use FileZilla.
Could you use WinSCP DLL - probably but you would need to spend time automating around it - meaning probably a lot more code than 4 lines of code to upload a file to the SFTP server from PowerShell using Transferetto. It's up to you which one do you prefer - I just create tools and share them :)
Here's winscp code: https://winscp.net/eng/docs/library_powershell
This is what I used to get around cert errors.
add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$result = Invoke-WebRequest -Uri "https://IpAddress/resource"
https://stackoverflow.com/questions/11696944/powershell-v3-invoke-webrequest-https-error
You can use a calculated property to do this all in one line. In fact, the Powershell Tip of The Week on Calculated Properties has almost exactly what you want:
http://technet.microsoft.com/en-us/library/ff730948.aspx
get-childitem C:\share -recurse -force | where {!$.PsIsContainer} | Select Fullname,LastAccessTime,@{N="Days since last access";E={ (((Get-date) - $.LastAccessTime).Days)}} | export-csv .\stuff.csv -notype
Note you should add -force to your get-childitem so it includes hidden items as well. Also, if you are using Powershell 3.0 you can add the -File parameter instead of having to do a where-object {!$_.PsIsContainer}
Say you have a .csv file with a lot of user names that you have to perform an action with, but you want to skip a specific one.
$Users = Import-CSV H:\Users.csv
foreach ($User in $Users){ if ( $User -eq "oneZergArmy" ) { ## Go to next item in loop continue
} }
$Users | ForEach-Object { if ( $PSItem -eq "oneZergArmy" ) { ## Go to next item in loop return
} }
https://stackoverflow.com/questions/7760013/why-does-continue-behave-like-break-in-a-foreach-object
howdy IWishItWouldSnow,
this covers changing from CMD.exe to powershell.exe, but i presume one could use the ISE executable instead.
Replace Command Prompt With PowerShell On Power User Menu In Windows 10
- http://www.addictivetips.com/windows-tips/replace-command-prompt-with-powershell-on-power-user-menu-in-windows-10/
take care,
lee
WinSCP has a powershell module that's been working great for SFTP etc. I remember I had to put the module files into the Powershell module directory and load from there. It would make all sorts of BS if I tried loading it from a custom folder for instance.
howdy decepere,
i presume this is the one you are talking about. [grin] i remember playing with it - and it was pretty nice! also, it seems to be still getting developer attention.
FastCopy
— https://fastcopy.jp/en/
take care,
lee
I don't know about a validator but as a starting point check out the free e-book 'The Community Book of PowerShell Practices'
The book is compiled by Don Jones and Matt Penny and is based on community input and the debates that followed the 2013 Scripting Games.
Good stuff!
I disagree on one point:
#Don't resort to using the .NET Framework unless absolutely necessary
From my perspective, if the .NET Framework can do it better, faster, or with fewer dependencies, IMHO you should use the .NET Framework. That being said, I would probably avoid dependencies on .NET Framework later than 3.5, unless it is unavoidable.
Example: I would never use the ActiveDirectory module in a function I write if I could instead use System.DirectoryServices.AccountManagement from .NET (Example function to pull group members without ActiveDirectory module)
Adding to what others are saying around management buy in (which I think is key), I think you should also start by showing the very basic benefits you can get with source control, e.g.
Start off small and see if you can just showcase these benefits, e.g. commit a change that accidentally wipes out a method/whole script and show how easy it is to bring it back. I'm sure a git revert
is a lot simpler than trying to retrieve a file system backup.
I would also find a good UI tool to help people through the process. If they are resistant to moving to source control I assume they would be resistant to using the git cmdline so having a good application is key. I haven't used a GUI for git in a while so I don't know if it is still relevant but I found SourceTree was great. Some editors, like VSCode, have git inbuilt and that makes things really helpful.
One thing you want to avoid is just showing everything and delving into the more advanced features like branching right off the bat. Git (if you choose that) can get really complex and I know it has put some people off due to some people's workflows.
I can't help you on the content part, but the first thing you need to do is get rid of those line continuation backticks asap. Powershell has a lot of methods for line continuation, here is a fantastic article that I always refer to: https://get-powershellblog.blogspot.com/2017/07/bye-bye-backtick-natural-line.html
That being said, I found a space after one of your backticks which completely breaks the string (this is why backticks are bad!). Here is a quick cleanup:
$FileString = "C:\temp\file.txt" $filebodytemplate = [System.Text.Encoding]::GetEncoding('utf-8').GetString([System.IO.File]::ReadAllBytes($FileString))
### Part of multipart, serves to limit and can be freely selected, but is not allowed to be in the sended file
$boundary = "PowerShellBoundaryInCodeExample123"
$BodyAttempt2part =
"Content-type: multipart/form-data, boundary=$boundaryr
nr
n" +
"--$boundaryr
n" +
"content-disposition: form-data; name="body
"r
nr
n" +
"This is an automated test with attachment from powershellr
n" +
"--$boundaryr
n" +
"Content-disposition: form-data; name="groupId
"r
nr
n" +
"$groupIDr
n" +
"--$boundaryr
n" +
"content-disposition: form-data; name="attachment1
"; filename="filetest.txt
"r
n" +
"Content-Type: text/plainr
n" +
"$filebodytemplate" +
"r
n--$boundary--"
$response = Invoke-RestMethod -Method POST -URI "https://www.yammer.com/api/v1/messages.json" -Headers $header -Body $BodyAttempt2part $response
https://www.amazon.com/dp/1617294160/ref=cm_sw_r_cp_apa_fabc_r74aGb8T88YNW
That book helped me learn all the basics and then some that I needed, when I started learning powershell. I still use it as a reference for writing scripts even after reading it too. It is super helpful and gets you learning the shell, the syntax of the script, and how to find information in the shell to do what you need. I can't recommend this enough.
I would rewrite the script to use the ADSI class type, which doesn't need the RSAT cmdlets. It's kind of limited, but works for basic operations like this. Here's an article about it.
http://technet.microsoft.com/en-us/magazine/2007.06.powershell.aspx
Post up the script if you need some help, I used to write a lot of these before the RSAT tools came out.
You are looking for Lateral Movement.
https://www.cloudflare.com/learning/security/glossary/what-is-lateral-movement/
Hi folks!
This is the video from my presentation with the Mississippi PowerShell User Group on working with PowerShell runspaces. Had a great time talking about this topic and hopefully everyone enjoys it!
The slide deck and demo code used is available below in the folder titled 'Art of PowerShell Runspaces'.
I recommend running the following command once:
"Set-PSReadLineKeyHandler -Key Tab -Function Complete" >> $PROFILE
then re-opening PowerShell. It changes the tab-completion behavior from cycling through each option individually one after another to showing all at once. Much better. Tab-completion is when you start typing a command or a parameter of a command and then just hit tab once or twice to have the rest of what you've typed filled in instantly - doing that also makes typos impossible
Use Visual Studio Code to write/run your commands and scripts, it's what you'll be using at some point anyway so doesn't hurt to start early and with the ms-vscode.powershell
extension it will point out some bad practices and suggest fixes in what you've written
Also, on the off-chance that you're not on Windows 10 - definitely get Windows 10, PowerShell has gotten so so much better with it - saves you a lot of headaches compared to what it was like under Windows 7 or even 8
> Is there a way to permanently edit this so that I do not have to keep inputting it for new sessions?
Drop it in the $profile. If you've done any Linux work, the $profile is the Powershell analog to the .bashrc.
Set the policy to RemoteSigned, problem solved. If the script is running from the local machine, it won't need to be signed but if its running from a network drive or any other non-local location, it will need to be signed.
[EDIT]
Add link to execution polices: http://technet.microsoft.com/en-us/library/ee176961.aspx
choco install powershell-core
then deploy powershell script scheduled task via GPO
choco update all -y
have all our admin support tools installed via choco and the scheduled task runs on all our servers once a week to keep everything up to date.
Having a little problem understanding why you would want that. Not taking your question too literally, I would suggest;
Look into Chocolatey.
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072;
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
When that is done, you can do things like:
choco.exe install -y --force --pre powershell-core
choco.exe install -y --force git
choco.exe install -y --force googlechrome
choco.exe install -y --force vscode.install
For a list of supported packages:
choco list
You might just want to use powershell to perform the FTP actions
https://stackoverflow.com/questions/1867385/upload-files-with-ftp-using-powershell
I believe there's even someone who wrote a module to work with FTP.
A while back, Jeffrey Snover indicated that DSC would be added to the Common Engineering Criteria, and that product teams have been informed of this pending addition.
What does this mean? We're starting to see DSC resources from other product teams, and this will only grow!
If you've been around PowerShell long enough, you know that the inclusion in the CEC as the standard for automation has driven the wonderful interoperability behind the language, allowing it to become the glue language that it is today.
DSC is still young, and has the same problems you see with any young and quickly growing technology, but exciting times ahead given the momentum and pressure behind this. I would highly recommend you at least start playing with it. The DSC Book is a decent start, and there are many more resources available online...
I'm certain there's a way to do it with Powershell (since you can do damn near anything with enough code), but choose the right tool for the job.
wget has a built-in switch to mirror a website/URL, including following links & retrieving images. Minimal additional scripting needed.
It sounds like your complaints are solely with the shell itself, and not the language--is that fair? Do grab psreadline mentioned ITT, it'll help. Otherwise, have you tried any alternate shells, like console 2, cmder?
Here, have a ball: https://chocolatey.org/packages?q=console
You should take a look at Ninite...it will silently install most apps you would use in a basic user configuration. But if you feel that PowerShell is the way to go, take a look at Chocolatey.
You might want to consider loading the WinSCP .NET Assembly straight into PowerShell. Then you can do everything inside of your script giving you better control and error handling.
100% agree with every post here so far. (Good advice and questions, /u/3diddy, /u/TheIncorrigible1, /u/arichtman, /u/Giordy77, /u/xradionut, /u/Windowsadmin, /u/uelmo, /u/dstrait!)
To summarize: it depends.
If you want to expand your mind, learn a totally different language:
If you want to directly amplify your PowerShell capabilities, C# or VB.Net.
SQL: I'll just leave this here.
It really just depends what you're interested in doing next.
This should do something along the lines of what you want, though I am not sure if it is the best way. This would fail if you ever had a ')' that you also wanted to keep that is inside the "WhatIWant", or if there were two }} in a row that was not the end of the structure.
$input -replace '{{collapse((.?))[\s\S]?}}', '$1'
A good place to test / learn regex is a site called RegExr. With PowerShell it is important that the '$1' is in single quotes (if you want to use double quotes then you need to escape the $ with ` , a back tick) to prevent it from being treated like a PowerShell variable.
The above regex with match the {{collapse\( that begins the structure, then match and create a capture group of anything inside the two \(\), then match anything between that until it runs into two }} in a row right next to each other. Then the replace command will take that match and replace it with the first, $1, capture group.
Are you trying to speed up data entry into some GUI that can't be managed with PowerShell and doesn't have an API?
AutoIt, or another macro utility might be a better fit, rather than trying to accelerate a human.
Remember: >To participate, add your solution to a public Gist (http://gist.github.com; you’ll need a free GitHub account, which all PowerShellers should have anyway). After creating your public Gist, just copy the URL from your browser window and paste it, by itself, as a comment on the PowerShell.org post, not this Reddit post please.
The Puzzle
Write a one-liner that produces the following output (note that property values will be different from computer to computer; that’s fine).
PSComputerName ServicePackMajorVersion Version· BIOSSerial · · · · · · · · · · · · · · · ·-------------- ----------------------- -------· ---------- · · · · · · · · · · · · · · · ·win81· · · · · · · · · · · · · · · · 0 6.3.9600 VMware-56 4d 09 1 71 dd a9 d0 e6 46 9f
By definition, a one-liner is a single, long command or pipeline that you type, hitting Enter only at the very end. If it wraps to more than one physical line as you’re typing, that’s OK. But, in order to really test your skill with the parser, try to make your one-liner as short as technically possible while still running correctly.
Challenges:
•Try to use no more than one semicolon total in the entire one-liner
•Try not to use ForEach-Object or one of its aliases
•Write the command so that it could target multiple computers (no error handling needed) if desired
•Want to go obscure? Feel free to use aliases and whatever other shortcuts you want to produce a teeny-tiny one-liner.
Good luck everyone!
Dive deeper into .NET itself. Download Visual Studio Community and learn C#
It's the path I took - I still use PowerShell for lots of things as it's quite quick to chain a few commands to get the job done, but the insight you get from learning .NET in C# helps immeasurably.
C# has something called LINQ which you will find very familiar. Where and Select syntax. It's pretty sweet.
So, it turns out that moving files that contain brackets, which mine does, is a bit weird. But I got it working with this:
# Moves all files into folders of same name Get-ChildItem -Path . -File | ForEach-Object { Move-Item -LiteralPath $.FullName -Destination $.BaseName }
Thanks for your help
Your updated code is in error. OutputFile should be a complete filename, ie "C:\MyFolder\ZoomInstaller.msi"
The issue that I am seeing is that they don't list a version number online and the version number is also not listed in the File Information. That may make it difficult to know when you need to download the newest version.
This worked for me:
Invoke-WebRequest -Uri https://zoom.us/client/latest/ZoomInstallerFull.msi -UseBasicParsing -OutFile C:\TechSupport\ZoomDirect.msi
I do it this way as well.
I tend to use https://codepen.io/ to get a design of the layout then i copy the html from it into a string and replace the values with variables as needed.
I also tend to integrate bootstrap into the html to make it easier to work with.
Here is an example. Tried to comment on what is going on.
#Decide what you will loop through $domainControllers = Get-ADDomainController -filter * | select -ExpandProperty name
#Count what you will loop through $totalCount = $domainControllers.count
#Initialize a counter $count = 1
#loop through all objects foreach($dc in $domaincontrollers){
#use write progress Write-Progress -Activity "Checking domain controller time sources" -status "Checking time source for $dc" -PercentComplete ($count / $totalCount * 100)
#Run some command(s)
if(test-connection -ComputerName $dc -quiet -count 2 -BufferSize 16){
w32tm /query /computer:$dc /source
}
#Increment the counter $counter++
}
A few references:
Side note: You may want to see verbose information, I find this helpful and try to use write-verbose to document my scripts now. To see these by default, set the $verbosepreference variable to continue. To go back, set it back to silentlycontinue.
$VerbosePreference = "Continue"
#Anything running here will run in verbose mode if available.
$VerbosePreference = "SilentlyContinue"
you can use robocopy with /Z, it automatically will retry and pick up where it left off.
(Robocopy and it's various parameters are kind of a pain to deal with in PS, but it's doable)
I wrote a massive module that performs a variety of esoteric email operations that we need for one reason or another. For example, it takes a user's Inbox and copies the entire contents to some folder as .msg files, complete with the original folder structure.
Another example: it can take a .PST file and copy the contents into a SQL database: sender, recipient, subject, body, attachments, etc... each is a field in the database where the respective data gets copied.
It can also perform all these operations in reverse, i.e. from SQL to .PST or account Inbox, etc.
The set of commands in the module makes full use of pipelining so that precisely the data needed is processed via the use of filters and stuff.
It's unusual because the time investment put into writing it versus its relative uselessness still astounds me sometimes.
EDIT: Bah. Since so many of you want to see this, then here it is: do with it what you will. Standard disclaimer here: I make no warranties and may not provide support, though I would be interested in thoughts in general on it. This will probably not even work for you unless it is heavily modified for your specific use-case scenario. As it is written, it expects administrative access to AD to read/write custom groups for permissions purposes. You may not want to go down this rabbit hole. You have been warned.
Why don't you push a trusted cert authority with a GPO and just sign your scripts?
Add a trusted root certification authority to a Group Policy object: http://technet.microsoft.com/en-us/library/cc738131.aspx
Signing PowerShell Scripts: http://www.hanselman.com/blog/SigningPowerShellScripts.aspx
If you're targeting Windows, you could install this Nuget package (Install-Package cmdlet):
https://www.nuget.org/packages/NFC-ACR122U/
That package would provide ReadData & WriteData methods to work with the device.
If you're targeting MacOS or Linux, it's not clear if it can be done.
Where would you get the updates from? There are some offline tools I have used in the past for standalone systems that could not be connected to a network. WSUS Offline
Why reinvent the wheel?
I love Powershell but there are plenty of tools that will do this for you. I've managed small fleets and built SOEs and I've never found a simpler way to deploy software than PDQ. It's not the most comprehensive tool, inventory management etc but it will save you a lot of time and it "just works" the free product is fine but the paid offering is good value.
Have you tried using the the WinSCP assembly directly? In a previous role i utilized this method to do all SFTP/FTPS things. Sadly I don't have access to those scripts anymore so I cannot provide a direct example.
The closest that I've come to building something in PowerShell and then rebuilding it in another language have been situations where I started fiddling around with some API or data or technique (because PowerShell makes it easy and fun), to the point where it became clear that PowerShell was not the right tool.
Examples:
Otherwise, like SeeminglyScience, I have a good sense at the outset that the final application will be developed in some other environment, but still use PowerShell to explore the problem space, sometimes even writing utilities that aren't part of the application but are still useful along the way.
You can use Newtonsoft.Json
to validate your JSON; just import the dll with Add-Type -Path ${path_to_newtonsoft.json.dll}
and have a look at this
For someone in your situation, I can't think of a better video to start with than this one: http://channel9.msdn.com/Events/TechEd/NorthAmerica/2014/DCIM-B318
And also watch this one: https://www.youtube.com/watch?v=j0EX5R2nnRI
They don't teach you the language as much as the concepts and ideas behind it. It helps answers the question "Why Powershell?".
Hey,
Remember that the power of PS is objects and pipeline. You are essentially not taking any advantage of that in your script. I would recommend that you watch some tutorials by Don Jones. He's a great teacher. In several of his videos, he is in fact creating a script very similiar to this. After doing that, delete your current code and start over.
What version of PS are you using? Get-ADComputer / Get-ADUser has gotten a lot better now, so there's really no reason to install the QAD-tools.
I'm not really sure how you want this script to work. The normal approach would be something like
Get-ComputerInfo -computername joe-pc
and it would spit out whatever info you want it to spit out.
Looking at your text, it would seem like you want to make a script that goes out searching through all computers to see which one Joe is logged in to, and then try to grab the info. Also, if the computer won't respond to ping, the script will probably not be able to grab any info anyway. For this to work, it would have to scan every computer "all the time", which seems a little silly.
While I absolutely suggest that you keep trying to write Powershell scripts, I would also suggest that you take a look at the free PDQ Inventory tool, which will make this a whole lot easier for you now. It will scan all computers at any given time, get every possible piece of info etc and show it in a pretty GUI.
I'll be happy to help you out after you've seen some Don Jones tutorials :) Here are two good ones:
http://channel9.msdn.com/Events/TechEd/NorthAmerica/2012/WSV321-R http://channel9.msdn.com/Events/TechEd/NorthAmerica/2014/DCIM-B418#fbid=
Windows will limit the number of conditions you can have in an event log query, and I don't think there's a way around that besides retrieving all events and manually processing them in the script. I learned about this from Winlogbeat which is also affected.
You can have everyone use the github for Windows client and just dump everything onto a network share. No dedicated server or services required. That's a zero cost solution and the guy client will help lower your learning curve (keep working towards she'll usage though).
If you're a Windows shop your developers might already have a TFS (Team Foundation Server aka MS version control). TFS 2015 supports git instances and you can use the github for Windows client with it as well.
It is not free for enterprise use by this definition:
​
>An “enterprise” is any organization and its affiliates who collectively have either (a) more than 250 PCs or users or (b) one million U.S. dollars (or the equivalent in other currencies) in annual revenues, and “affiliates” means those entities that control (via majority ownership), are controlled by, or are under common control with an organization.
​
I would highly suggest you read the full licence terms as Microsoft don't play games when it comes to terms of use when their auditors knock on the door. https://visualstudio.microsoft.com/license-terms/mlt553321/
Couple of ways you could do it (each come with caveats though):
GitLab - never used it myself, but several people I've talked to swear by it.
MyGet
Happy to hear you have it working.
VSCode is a very nice editor, if you do use it I would suggest to follow Mike Robbins guide on setting it up. http://mikefrobbins.com/2017/08/24/how-to-install-visual-studio-code-and-configure-it-as-a-replacement-for-the-powershell-ise/
OK, so it looks like you are not too far off. I just added the following and was able to create a new list.
$CreateBody = @{
'name' = "MyChecklist"
'public' = 0
} | convertto-json
$WRCreate = @{
URI = "https://checkvist.com/checklists.json"
Body = $CreateBody
method = 'POST'
contenttype = "application/json"
Websession = $test
}
$WR4 = Invoke-Webrequest @WRCreate PS C:\Windows\system32> $wr4.Content | convertfrom-json
id : 596960 name : MyChecklist options : 3 public : True updated_at : 2017/01/26 20:17:57 +0000 markdown? : True archived : False read_only : True user_count : 1 user_updated_at : percent_completed : 0 task_count : 0 task_completed : 0 tags : tags_as_text :
Couple things to take note of. Parameters: checklist[name] - checklist name checklist[public] - 0|1 (optional) The Actual parameter names are: name public
So your body would be a hashtable with name and public, values could be 'mylist' and the public would be 0 for false and 1 for true(I think)
You then have to convert the body to json, as that is what the API expects. It could be XML, but I would go with json as it is easier to convert to and from in Powershell.
Let me know if you need another example.
It might be better to override the function. https://msdn.microsoft.com/powershell/reference/5.1/Microsoft.PowerShell.Core/about/about_Command_Precedence
This has a good example on how to do it: https://stackoverflow.com/questions/33747257/can-i-override-a-powershell-native-cmdlet-but-call-it-from-my-override
Edit: Don't know if the following even works.
function Send-MailMessagee { process{ Microsoft.PowerShell.Utility\Send-MailMessage $_ -Subject '' } }
Yes, it should be possible to do all of that.
To detect drive attached: http://superuser.com/questions/219401/starting-scheduled-task-by-detecting-connection-of-usb-device
Use robocopy to copy the files
Use a method from the win32_volume class to change drive letters and another to dismount the drive
Use send-mailmessage to send mail on completion
You're right, less than 10 minutes.
Open PowerShell Script with AHK
copy-item 'C:\GameFiles' -Recurse C:\GameFilesBackup
This is a feature of PowerShell 5 (Also available on older versions of PowerShell by installing the "PSReadline" module.)
As far as I know there is not a way to straight out disable this.
You could (this is not a elegant solution): Change the colours of each of the "Tokens" to White, eg. Comment, Parameter
Example: Set-PSReadlineOption -TokenKind Comment -ForegroundColor White
More reading:
http://superuser.com/questions/996175/powershell-command-highlighting/996186 http://superuser.com/questions/950875/how-to-set-custom-syntax-coloring-for-powershell-5-0
While I'm no powershell expert, that sounds perfectly possible.
But, me also being more of a *nix guy, I have to say that you can do pretty much everything you ask for in Python too, even the Outlook stuff.
I wouldn't try to parse the web page as a string. Powershell can parse XML natively. Use the id
and class
attributes to get the info you need.
Something like this:
$url = "http://bing.com?q=flight status for $query"
$result = Invoke-WebRequest $url
$result.AllElements | Where Class -eq "ans" | Select -First 1 -ExpandProperty innerText
Source: https://stackoverflow.com/questions/9053573/powershell-html-parsing-get-information-from-a-website
It is really hard to follow your code given the formatting, obfuscation, lack of data, output and so on. See create a Minimal, Complete, and Verifiable
In any case if the question is can I aggregate many lines with similar value together the answer is probably in a Group-Object
.
At some point take your results an and group based on the name. You would then probably need to use Select-Object or some other manipulation to convert the Group-Object
results into a flat hash/array/object that can be exported to CSV.
PS C:\Users> Get-Service | Group-Object Status
Count Name Group ----- ---- ----- 100 Running {AdaptiveSleepService, AMD External Events Utility, AppIDSvc, Appinfo...} 141 Stopped {AJRouter, ALG, AppReadiness, AppVClient...}
PS C:\Users> Get-Service | Group-Object Status | Select-Object Name, @{Name="Services";Expression={ $_.Group.Name -join ";" }} | Format-List
Name : Running Services : AdaptiveSleepService;AMD External Events Utility;... Name : Stopped Services : AJRouter;ALG;AppReadiness;AppVClient;AppXSvc;...
Okay so a bit of rundown, a hypervisor is the software that allows the management of virtual machines known as Guest Operatin Systems.
The host (hypervisor) has a couple of different types, theres type 1 which exist as its own entity installed directly onto the harddrive as the system. The most popular of these are known as VMware ESXi and Micorosoft Hyper-V.
Type 2 exists on a pre-existing operating system, Virtualbox, VMware Player, VMware workstation are the most popular but there's certainly others.
With type 1 hypervisors they are designed to be** always running** and act as the** dedicated host** with no further roles installed onto them. So using your Windows 10 desktop is not recommended (although you can... https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/quick-start/enable-hyper-v).
ESXi needs to be managed by a web browser or client application called Vsphere, and doesn't have a standard desktop like Microsoft implementation.
Virtual Box This software is freely available type 2 hyper-visor (install it on your desktop and it is open source: https://www.virtualbox.org/
Uness I'm deploying onto server infrastructure for a client I prefer Virtualbox as it seems to have the most readily available features and of course is open source.
Just a note, as I have dealt with this before.
Cryptolocker stores a list of all the affected files in the registry.
> How to find files that have been encrypted by CryptoWall
When CryptoWall encrypts a file it will store the file and its path as a value in the Windows Registry. The location of the subkey is in the following format: HKCU\Software<unique computer id><random id>
With an actual example being HKCU\Software\03DA0C0D2383CCC2BC8232DD0AAAD117\01133428ABDEEEFF. CryptoWall will then create a value for each file that it encrypts under this key.
http://www.bleepingcomputer.com/virus-removal/cryptowall-ransomware-information
may help to find files that are important to recover, and lets you know which directories have been affected.
Yeah, thats not how you use paramaters.
The paramater would be used when you run your script.
Example:
my-script.ps1:
Param( [string]$myInput )
echo "Hello $myInput"
Now run myscript.ps1 with the input "world".
>my-script.ps1 -myInput "world" >Hello world
For all you need to know about parmaters see: http://technet.microsoft.com/en-us/magazine/jj554301.aspx
If something that you want to interact with has a REST API available to use. That would probably be the best route to go with. Invoke-RestMethod is used a fair bit, even in that Todoist module.
For IFTTT have a look at this: https://ifttt.com/maker_webhooks
git's origin is Linux kernel development. There are countless managed git service - Github is just one of those and some are also available as self-hosted versions, e.g. GitLab or Gitea.
git is not even installed on many Linux distributions by default so why do you expect this to be the case on Windows?
That's why installation instructions for all major platforms can be found on the official git page: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
A text expansion program would probably work very well for this, at least for yourself.
I think others are right about github for sharing overall.
Windows Environment with AD CA ?
And Signing with:
$Cert = Get-ChildItem Cert: --CodeSigningCert Set-AuthenticodeSignature File.exe -Certificate $Cert
You could also create a self signed code sign with "makecert"
For more details see: https://stackoverflow.com/questions/84847/how-do-i-create-a-self-signed-certificate-for-code-signing-on-windows
try setting the $Password variable value with 'singlequotes' instead of "double"
https://stackoverflow.com/questions/22335651/powershell-invoke-sqlcmd-login-failed
-> http://www.computerperformance.co.uk/powershell/powershell_quotes.htm
Sysinternals (now msft) psloglist.exe will allow you to run this from a central script.
psloglist @machinelist.txt -d 1 -f we System
Will grab every machine in the file machinelist.txt for the previous 1 day, and filter out only warnings and errors and dump the System log.
http://technet.microsoft.com/en-us/sysinternals/bb897544.aspx
For importing the list of computer names I would use Import-CSV
With a list of computer names each on it's own line you essentially end up with a single column table that is then passed to your loop.
> So my environment is super locked down and it’s rare for it to approve additional downloads.
ShareX can run in portable mode. No installation required.
>Can sharex be controlled programmatically through power shell?
Probably, or certainly by calling a batch file. Many command line options:
https://getsharex.com/docs/command-line-arguments
>Does it capture whole web pages even when the webpage requires scrolling to see entirety of page?
Yes.
Welcome to PowerShell...
Use Invoke-WebRequest to download the file.
(example at http://powershell.com/cs/blogs/tips/archive/2012/10/11/downloading-files-from-internet.aspx )
It's not pretty, but this is how you would unzip a file:
[System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') [System.IO.Compression.ZipFile]::ExtractToDirectory($sourceFile, $targetFolder)
(via http://serverfault.com/questions/18872/how-to-zip-unzip-files-in-powershell)
this might be a place to start
here's an example
$domain = new-object DirectoryServices.DirectoryEntry('LDAP://test.test.com','DOMAIN\user','pass') $searcher = [System.DirectoryServices.DirectorySearcher]$domain $searcher.searchRoot = [adsi]'LDAP://OU=Something,DC=domain,DC=com' $searcher.Filter = '(samaccountname=john.smith)' $searcher.FindOne()
but you'll have to google around how to use adsisearcher in powershell to get the results you want. this is what i created for adsisearcher, but you'll likely have to pick what you want from it to build a script for your scenario.
https://github.com/gangstanthony/PowerShell/blob/master/Get-MyADObject.ps1
That's what https://repl.it/ is for, learning and using languages other than JavaScript, using only a browser. They have a free offering, and their classroom version is free for public K-12 schools and non-profits. (And you can scroll down and click one of the languages, no need to sign up or log in)
You can also do the same thing with GitLab CE if you want to self host and keep everything inhouse.
As for in general setting up runners. It's probably best to have people clone from main/master to their own repo, they create a new branch, make their changes in their repo, then push that branch to the repo they cloned from. This allows you or other maintaining the repo to more easily merge changes and track what everyone is working on. If you don't do something like this then you end up with people making changes directly to the main/master branch and it quickly becomes a mess to manage.
Edit: As for the runner, you can trigger off of many things like approvals, merges, pushes and what not. You likely want to trigger off of merges to the main/master branch. Then have a script pull the scripts down, look for scripts with no signatures, sign them, then push it's changes back to main/master.
>Every sys admin develops and tests their scripts locally and then pushes them to some central code repository (git probably?) .
You need source control the moment your team expands to greater than 0 members.
GitLab Community Edition is free and can be hosted in your environment. If you've used GitHub previously, the workflow should feel familiar.
But GitHub has a free private repository offering as well, if you're OK w/ hosting stuff there. If you're already on Office 365/Azure, there's Azure DevOps too which may be a good fit.
Passing arguments using @args is called "splatting". It lets you pass arguments to a cmdlet/function using a hash table. For example, New-Mailbox accepts the "Name" and "Alias" parameters. Typically, you'd pass them as:
New-Mailbox -Name "Kim Akers" -alias kim.akers
Splatting allows you to separate the arguments and the command, allowing you to pass the same set of parameters multiple times, append to parameter sets etc.
This article explains splatting well.