Quantcast
Channel: Hey, Scripting Guy! Blog
Viewing all 3333 articles
Browse latest View live

Write and Run PowerShell Script Without Scripting

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about writing and running a Windows PowerShell script without scripting.

Hey, Scripting Guy! Question Hey, Scripting Guy! I like using the Windows PowerShell ISE, but I do not have rights to run a script. I am stuck using a twenty year-old command prompt with Windows PowerShell inside. What’s up with that?

—DM

Hey, Scripting Guy! Answer Hello DM,

Microsoft Scripting Guy, Ed Wilson, is here. This afternoon I am sipping a cup of Gunpowder green tea, with a bit of fresh lemon juice in it. It is a nice refreshing treat for a midafternoon slump. Of course, the biscotti also helps. Anyway...

DM, welcome to Script Without Scripting Week. Because you use the Windows PowerShell ISE, does not necessarily mean that you are scripting. In fact, you can write a script and run a script, and still not be scripting.

I have pretty much quit my exclusive use of the Windows PowerShell console, and I do nearly all of my Windows PowerShell work inside the Windows PowerShell ISE. But unless I am doing something complex, I do not bother writing a script. I just use the Windows PowerShell ISE as a better, more modern console. If I choose to write in the upper-script pane or type directly in the interactive pane is more a function of whether my command will be one line or longer.

Even if have your script execution policy set to Restricted, you can still use the Windows PowerShell ISE. For Windows PowerShell purposes, a script is not a script until it reads from the disk. So all commands typed in the script pane and executed are simply Windows PowerShell commands, and they are not subject to the script execution policy. However, when you save the code to a file, the next time you run it, it will be a script. Here is an example:

Image of command output

When I save the script as a file, and then I attempt to run the script, the following error message appears to inform me that running scripts is disabled:

Image of error message

If I open the script in Notepad, copy the contents to the clipboard, and then paste the script into a new Windows PowerShell ISE pane, I can run the script as I did before. This is shown here:

Image of command output

Using bypass

There are many ways to run a Windows PowerShell script when the execution policy is set to Restricted. But the easiest way is to launch Windows PowerShell with the bypass execution policy. Here is the command:

powershell -executionpolicy bypass

As shown here, I type this command in the Run dialog box:

Image of dialog box

This command launches the Windows PowerShell console in bypass mode. But what about the Windows PowerShell ISE? Let's try to use the following command:

powershell_ise -executionpolicy bypass

I receive an error message that says there is no such parameter:

Image of error message

So what do I do? As shown here, I can use the simple ISE command inside the Windows PowerShell console that I launched in bypass mode:

Image of command

Now I go to my newly opened Windows PowerShell ISE, and I see that it is in bypass mode. I then open and run my Windows PowerShell script:

Image of command output

DM, that is all there is to using the ISE without scripting. Script Without Scripting Week will continue tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 


PowerTip: Use PowerShell to Show Illegal File Name Characters

$
0
0

Summary: Use Windows PowerShell to display illegal characters for a file name.

Hey, Scripting Guy! Question How can I use Windows PowerShell to easily obtain a list of characters that are not permitted in file names?

Hey, Scripting Guy! Answer Use the GetInvalidFileNameChars static method from the System.IO.Path .NET Framework class:

[System.IO.Path]::GetInvalidFileNameChars()

Avoid Scripting: Use PowerShell Command History

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about avoiding Windows PowerShell scripting by using command history.

Hey, Scripting Guy! Question Hey, Scripting Guy! I used to have a program that I could use to keep track of commands I typed at the command prompt. It permitted me to use macros to replay those commands or to select which commands I wanted to run. It was simple, elegant, and not complicated. It is a shame that “modern” programs are not that easy to use. I really don’t relish the thought of having to learning scripting to be able to run a few commands. I wish I could go back to my old command prompt. But I guess I cannot. No action required. I am just letting off steam today. Thanks for listening.

—LM

Hey, Scripting Guy! Answer Hello LM,

Microsoft Scripting Guy, Ed Wilson, is here. The Scripting Wife and I were out and about the other day, before the snow storm hit, and we ran across a little tea shop that had a very nice Lapsang Souchong tea. It is one of the few teas that I drink with milk. I find I need the milk to help cut the rather strong, unique flavor. If you haven’t had this tea, you may want to try it sometime—but don’t rush out and buy a pound of it just yet. It is a bit of an acquired taste, and you might not like it.

It is a good tea to try off a nice tea menu to see if you like it. I find it goes really well with Scottish butter cookies—but again, that may be me. I find the combination to be a bit “old school”;  but then, it may be that I fell in love with the combination a long time ago when we were in Australia for the first time.

Speaking of old school...

Yeah, I think I may remember using an old-fashioned command prompt a long time ago. It was simple—but I also remember some of the commands were pretty convoluted, and they all seemed to act differently. The good thing, LM, is that you can use the Windows PowerShell console in a similar fashion to how you used the command line. You do not have to learn scripting if you do not want to. All you need to do is to use the command history.

Windows PowerShell command history

There are a number of Windows PowerShell cmdlets that permit working with the command history. I can find them by using the Get-Command cmdlet, and then looking for a name that matches History and a command type that equals Cmdlet. Here is the command and the results:

PS C:\> Get-Command -Name *history* -CommandType cmdlet

CommandType     Name                                        ModuleName

-----------               ----                                               ----------

Cmdlet          Add-History                                        Microsoft.Powe...

Cmdlet          Clear-History                                     Microsoft.Powe...

Cmdlet          Get-History                                        Microsoft.Powe...

Cmdlet          Invoke-History                                    Microsoft.Powe...

To see the commands in my history, I use the Get-History cmdlet:

PS C:\> Get-History

  Id CommandLine

  --   -----------

   7 clhy

   8 cls

   9 h

  10 cls

  11 Get-Command -Noun history

  12 cls

  13 Get-Command -Noun history -CommandType cmdlet

  14 Get-Command -Noun history -CommandType Cmdlet

  15 Get-Command -Noun history

  16 Get-Command Get-Command -Syntax

  17 cls

  18 Get-Command -Name *history* -CommandType cmdlet

If I find myself using the Get-History cmdlet often, I can use an alias. Here is the Get-Alias command:

PS C:\> Get-Alias -Definition Get-History

CommandType     Name                                     ModuleName

-----------               ----                                            ----------

Alias           ghy -> Get-History

Alias           h -> Get-History

Alias           history -> Get-History

If I want to run a command from the history, I use the Invoke-History cmdlet. I generally use Get-History and Invoke-History together. I need to see what is in my history before I can execute a prior command. The easiest way to run something from the history is to specify the command ID. This technique is shown here:

PS C:\> Get-History

  Id CommandLine

  --     -----------

  21 clhy

  22 cls

  23 Get-History

  24 cls

  25 Get-Service bits

  26 Get-Process explorer

  27 cls

 

PS C:\> Invoke-History -Id 25

Get-Service bits

Status   Name               DisplayName

------        ----                   -----------

Running  bits               Background Intelligent Transfer Ser...

As shown here, I can specify an array of ID numbers for the Get-History cmdlet:

PS C:\> Get-History -Id 25, 26

  Id CommandLine

  --    -----------

  25 Get-Service bits

  26 Get-Process explorer

But when I attempt to use an array of IDs with the Invoke-History cmdlet, I get the following error message:

Image of error message

Hmmm…

Well, I can pipe the results from Get-History to Invoke-History:

PS C:\> Get-History 25 | Invoke-History

Get-Service bits

Status   Name               DisplayName

------       ----                   -----------

Running  bits               Background Intelligent Transfer Ser...

Because I can get multiple items from the history, can I also pipeline them? As shown in the following image, I still get an error message:

Image of error message

Bummer.

When I see an error message that says a cmdlet will not accept multiple items through the pipeline, I can usually substitute the command for one that includes Foreach-Object. This is because Foreach-Object interrupts the pipeline and deals with each item, one at a time. It ruins “streaming” the output, but it permits me to pipe the results from one command to another. I can also automate the output without having to resort to scripting. Here is the revised command:

Get-History -Id 25, 26 | foreach { Invoke-History -id $_.ID}

As shown in the following image, the command works:

Image of command output

LM, that is all there is to using the Windows PowerShell command history. Script Without Scripting Week will continue tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Use PowerShell to Generate Random File Name

$
0
0

Summary: Use Windows PowerShell to generate a random file name.

Hey, Scripting Guy! Question How can I use Windows PowerShell to generate a random file name so I can ensure that
           a file I create does not have a naming conflict?

Hey, Scripting Guy! Answer Use the GetRandomFileName static method from the System.IO.Path .NET Framework
           class, for example:

[System.IO.Path]::GetRandomFileName()

Don’t Script: Edit PowerShell Command History

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about editing the Windows PowerShell command history.

Hey, Scripting Guy! Question Hey, Scripting Guy! I liked your ideas in Avoid Scripting: Use PowerShell Command History. My problem is that I seldom (if ever) type commands perfectly the first time—often, not even the second time. This means that I end up with a lot of junk in my command history. I wish there was a way to clean up the command history so it would be more usable. Is there?

—AP

Hey, Scripting Guy! Answer Hello AP,

Microsoft Scripting Guy, Ed Wilson, is here. This afternoon, I am listening to a Canadian rock group and sipping some pomegranate tea. Of course, pomegranate is not really a tea, and a pomegranate tea is actually an herbal fruit kind of concoction. But hey—it is still nice and refreshing, and it doesn’t have any caffeine in it. Along with chocolate biscotti, it makes a great way to work.

AP, another great way to work is to use your Windows PowerShell command history. It is actually very flexible, and it is pretty easy to edit the history if you want to do so.

Editing the Windows PowerShell command history is perhaps a misnomer. I cannot really edit the command history, but I can delete items from it and add items to it. I cannot edit an actual entry from the command history—well actually, I could, but I would need to export the history to a file, edit the file, and then import the history back in, which is a bit more work than I want to do. (If this was a scenario that I found myself doing on a regular basis, I could write a function to make it more doable.)

How do I remove stuff from my Windows PowerShell command history? I use the Clear-History cmdlet. I will admit that when I first saw this cmdlet, I thought that it...well...cleared all of my history from Windows PowerShell. And it will do that, of course. Here is an example:

PS C:\> Clear-History

PS C:\>

I type the command, and nothing returns. If I want to see a bit more information, I can use the standard –Verbose Windows PowerShell parameter. This will tell me that the command is clearing my Windows PowerShell command history. This is shown here:

PS C:\> Clear-History -Verbose

VERBOSE: Performing the operation "Clear-History" on target "This command will clear all the entries from the session history."

As shown here, I can also use the –WhatIf parameter if I am unsure that I want to remove all items:

PS C:\> Clear-History -WhatIf

What if: Performing the operation "Clear-History" on target "This command will clear all the entries from the session history."

But the cmdlet is more flexible than simply emptying my Windows PowerShell history. I could remove specific items from my Windows PowerShell history. Before I remove a specific item from the Windows PowerShell command history, I like to look at the command. I can do this by using the Get-History cmdlet and specify a specific ID number. I then pipe the results to the Format-List cmdlet so I can see more information than the standard output. Here is the standard output:

PS C:\> Get-History 67

  Id CommandLine

  --   -----------

  67 srv

Here is the more detailed output:

PS C:\> Get-History 67 | fl *

Id                 : 67

CommandLine        : srv

ExecutionStatus    : Completed

StartExecutionTime : 3/2/2015 3:15:36 PM

EndExecutionTime   : 3/2/2015 3:15:36 PM

Because a command completed (as did the previous command), it does not mean that it completed successfully. Here is what happens when I try to use the Invoke-History cmdlet (r is an alias) to execute the command:

PS C:\> r 67

srv

srv : The term 'srv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

At line:1 char:1

+ srv

+ ~~~

    + CategoryInfo          : ObjectNotFound: (srv:String) [], CommandNotFoundException

    + FullyQualifiedErrorId : CommandNotFoundException

Finding a specific command

So I have a command that doesn’t work in my Windows PowerShell command history. I can find all of these types of commands by using the Get-History command and piping the results to the Where-Object cmdlet. I already know that I have a property called CommandLine that contains my commands. Here is the command I use to find the commands:

PS C:\> Get-History | where commandline -eq 'srv'

  Id CommandLine

  --   -----------

  67 srv

  78 srv

  81 srv

Removing the bad commands from history

I thought I might need to pipe the results of my Get-History cmdlet to the Clear-History cmdet. But as it turns out, I don’t need to do that. I can use Clear-History to search for and remove my bad command:

Clear-History -CommandLine 'srv'

Sweet…no errors. Then I decide to use the Up arrow to recall my previous Get-History command. Bummer. I still have a couple of entries remaining:

PS C:\> Get-History | where commandline -eq 'srv'

  Id CommandLine

  --   -----------

  78 srv

  81 srv

I remember to use the count. I see that there are two instances of the bad command still in history, so I use the Up arrow and add the count. Here is my command:

Clear-History -CommandLine 'srv' -Count 2

Now when I use the Get-History command, nothing appears.

These commands and their associated output are shown in the following image:

Image of command output

AP, that is all there is to editing the Windows PowerShell command history. Script Without Scripting Week will continue tomorrow when I will talk about using code snippets.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Use PowerShell to Find Temp User Directory

$
0
0

Summary: Use Windows PowerShell to find the temporary user directory.

Hey, Scripting Guy! Question How can I use Windows PowerShell to find location of my temporary user directory?

 Hey, Scripting Guy! Answer Use the GetTempPath static method from the System.IO.Path .NET Framework class:

[System.IO.Path]::GetTempPath() 

Don’t Write Scripts: Use Snippets

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell snippets to avoid scripting demands.

Hey, Scripting Guy! Question Hey, Scripting Guy! One of the things that I find myself having to do from time-to-time is write scripts. I really don’t like to write scripts, but sometimes I cannot find what I need to, and I cannot avoid it. I really wish that when I do have to write a script, I could make it as painless as possible. Is painless possible?

—RA

Hey, Scripting Guy! Answer Hello RA,

Microsoft Scripting Guy, Ed Wilson, is here. Well tonight is the Charlotte PowerShell Users Group meeting. We will be having a guest presentation by Microsoft PFE, Jason Walker. Jason is a really cool dude, and he has written quite a few guest Hey, Scripting Guy! Blog posts (in fact, he is an Honorary Scripting Guy). So, the meeting tonight will be awesome. The Scripting Wife and I have been looking forward to it for a while.

RA, something else that is awesome is using Windows PowerShell ISE snippets to reduce the amount of scripting involved in creating a custom solution.

When I open the Windows PowerShell ISE, the first thing I need to do is start the snippets. To do this, I can type <CTRL +J>, or simply select Start Snippets from the Edit menu:

Image of menu

The snippet drop-down list appears and it shows me what snippets are available. The list is shown here:

Image of menu

If I hover my mouse over the snippet for a few seconds, the actual code that comprises the snippet appears. This will appear on the left if it is a long piece of code, such as the complete advanced function. It will appear on the right if it is relatively short, such as the comment block. Here is the comment-block snippet:

Image of script

If I want to insert the code snippet into my script, I highlight the snippet from the drop-down list, and press ENTER. The current insertion point in the script governs where the code snippet will appear. This means that I need to place my mouse cursor exactly where I want the snippet to appear in my script. So the following comment block appears at the beginning of my script because that is where my cursor is:

Image of command output

The cool thing about this snippet is that it moved my insertion point to the place where I would more than likely actually type. Of course, the fact that I have a comment in the middle of a comment block is a bit strange—but hey, it works, and it helps me avoid typing.

Now I decide to add a For loop. I move my insertion point after my comment block, and start the snippets again (I like to use <CTRL + J> because it keeps my hands on the keyboard). I select For from the drop-down list. The description tells me it is a For loop. I press ENTER, and voila! The For loop appears in my code.

The strange thing is that I am left on the For line, not in the code block. But I guess that makes sense because most of the time I am not going to loop 99 times. I add the output for $i into the script block, and I press the green triangle (or <F5>) to run my script. The output is shown here:

Image of command output

I place my insertion point after the $i that I added to the script, start the snippets again, and add an If statement to my script. I have to change the $x variable to $i, and set a condition that $i is equal to 5. I then add code in the script block so that the script will break when the $i condition matches. I then run the script again. The script and the output are shown here:

Image of command output

So I did very little typing, and in less than a minute, I had a script “that does something.” Windows PowerShell code snippets offer two advantages:

  1. They help if one cannot remember exact syntax. In this way, they often provide enough so that one can quickly get the code written without having to look up everything.
  2. They help an experienced scripter avoid a lot of typing. In this way, the snippets help save time.

RA, that is all there is to using Windows PowerShell ISE snippets. Script Without Scripting Week will continue tomorrow when I will talk about creating snippets.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

PowerTip: Use PowerShell to Identify Files Without an Extension

$
0
0

Summary: Use Windows PowerShell to identify files that do not have an extension.

Hey, Scripting Guy! Question How can I use Windows PowerShell to easily identify files that do not have an extension?

Hey, Scripting Guy! Answer Use the HasExtension static method from the System.IO.Path .NET Framework class, for example:

[System.IO.Path]::hasExtension("C:\fso\FileWithOutExtension")


Don’t Script: Create PowerShell Snippets

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about creating custom Windows PowerShell snippets.

Hey, Scripting Guy! Question Hey, Scripting Guy! Thank you for yesterday's blog post, Don’t Write Scripts: Use Snippets. I like the idea of having access to Windows PowerShell script snippets. But I used to create my own snippets. It made it easier for me to work, and I could create a custom script based on my snippets in less than 30 seconds. I don’t see anything like that these days. Am I missing something? Please help me understand.

—JT

Hey, Scripting Guy! Answer Hello JT,

Microsoft Scripting Guy, Ed Wilson, is here. This morning, it is raining. It looks like spring time outside. It is almost warm, and it really is damp. So, as a result, I got soggy on my way to the gym for my morning workout. To me, it just seems wrong to drive to the gym, so I always walk or run there. Anyway, after drying off and changing, I got on the treadmill to finish warming up.

Luckily, the gym has WiFi, so I was able to check the email sent to scripter@microsoft.com when I finished my workout. JT, one of the cool things about Windows PowerShell ISE snippets, is that I can easily create my own snippets. I can even save them, and copy them to other devices. This makes them really great to use. One thing to keep in mind is that I cannot create a new snippet if the execution policy is set to AllSigned or Restricted. I will get an error message.

Anything that I type over and over again in my Windows PowerShell scripts becomes fair game for a script snippet. Of course, the things I have a tendency to type over and over again tend to depend on what sort of a script I am writing.

For example, if I am working with Word, I will obviously need to create an instance of the Word.Application object. If I am working on a script that connects to remote servers, I usually query Active Directory Domain Services to obtain a list of servers. So, I might need to create multiple snippets that cover the basic types of scripts I tend to write.

The cool thing is that there is a New-ISESnippet cmdlet I can use to create a new snippet. I can call the cmdlet directly, or I can write a script to create the snippet. I can even overwrite an existing snippet with the same name by using the –Force parameter. I specify the title, the description, author information, and the text. The text is the actual content of my snippet. The –CaretOffset parameter specifies how far over the insertion point moves. This parameter requires a bit of experimentation to get it right. Here is an example of a script that creates a new ISE snippet:

New-IseSnippet -Force -Title "Basic Heading" -Description "Basic script heading info" `

 -Author "ed wilson" -CaretOffset 18 -Text "

 # Script name:

 # Script description:

 # Script category:

 #

 # Date:

 # Version: 1.0

 # "

When I run the script, the newly created snippet appears in the snippet list. (I use <Ctrl+J> to start the snippets, but I can also click Start Snippets from the Edit menu.) The newly created snippet is shown here in the drop-down list:

Image of menu

I select the snippet, press ENTER, and it is inserted into my new blank script file. This is shown here:

Image of command output

One thing to keep in mind is that even if I use the –Force parameter to overwrite existing snippets, if I run the script multiple times, I will get multiple instances of the snippet appearing in the snippet drop-down list. To fix this issue, all I need to do is to close the Windows PowerShell ISE and open it. The extraneous entries no longer appear in the drop-down list.

To delete a snippet, I use the Get-ISESnippet cmdlet and pipe the results to the Remote-Item cmdlet. This technique is shown here:

PS C:\> Get-IseSnippet

    Directory: C:\Users\ed\Documents\WindowsPowerShell\Snippets

Mode             LastWriteTime     Length    Name                                                       

----                -------------                  ------    ----                                                       

-a---          3/3/2015  10:33 AM        783 Basic Heading.snippets.ps1xml                              

PS C:\> Get-IseSnippet | Remove-Item

JT, that is all there is to creating your own script snippets. Script Without Scripting Week will continue tomorrow when I will talk about saving scripts from applications.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Encrypt Files with PowerShell

$
0
0

Summary: Learn how to easily encrypt files by using Windows PowerShell.

Hey, Scripting Guy! Question How can I use Windows PowerShell to easily encrypt files?

Hey, Scripting Guy! Answer Use the Encrypt static method from the System.IO.File .NET Framework class, for example:

[io.file]::Encrypt("C:\fso\FileWithOutExtension")

Weekend Scripter: Avoid PowerShell Scripting—Use GUI Tools

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about exporting queries from the event log tool.

Microsoft Scripting Guy, Ed Wilson, is here. It has long been a truism (at least with things related to computers): powerful is opposite of simple. I can have a tool that is powerful, but with that power comes complexity. When that complexity is so complex as to render the tool ridiculously hard to use, the tool rapidly becomes useless.

What is awesome is when a tool is extremely powerful and also very easy to use. Of course, this usually means that the tool makes lots of default choices for me. If those default choices are intelligent, I really don’t care. Microsoft Word is sort of like that. I mean, the default document template makes tons of choices. Usually, I do not care about the exact spacing between paragraphs, the default Tab stop, column width, or page length. Usually…

Of course, when I have to modify those things, I know I am probably going to have to set aside all day.

The Windows PowerShell cmdlet Get-WinEvent is often perceived to be such a tool. It is way powerful—but it is also more complicated to use, than for example, the Get-EventLog cmdlet. The problem with Get-EventLog is that it only works for legacy event logs. For all the newer (new as in Windows Vista era—so not really all that new at all) types of logs, I need to use Get-WinEvent. Because Get-WinEvent also works with legacy event logs, I have completely quit using the Get-EventLog cmdlet. This forces me to learn how to use the Get-WinEvent cmdlet.

One problem with the Get-WinEvent cmdlet, is at first glance, it is hard to figure out how to filter the results. It is a truism, that for performance sake, I filter to the left of the pipeline character. So this means that I do not use Get-WinEvent to return everything and then pipe it to the Where-Object.

This is especially true with some logs that return thousands of records. But how do I filter, for example, on an Event ID? Here is the syntax that shows the various parameter sets (ways of using the cmdlet):

PS C:\> Get-Command Get-WinEvent -Syntax

 

Get-WinEvent [[-LogName] <string[]>] [-MaxEvents <long>] [-ComputerName <string>] [-Credential

<pscredential>] [-FilterXPath <string>] [-Force] [-Oldest] [<CommonParameters>]

 

Get-WinEvent [-ListLog] <string[]> [-ComputerName <string>] [-Credential <pscredential>] [-Force]

[<CommonParameters>]

 

Get-WinEvent [-ListProvider] <string[]> [-ComputerName <string>] [-Credential <pscredential>]

[<CommonParameters>]

 

Get-WinEvent [-ProviderName] <string[]> [-MaxEvents <long>] [-ComputerName <string>] [-Credential

<pscredential>] [-FilterXPath <string>] [-Force] [-Oldest] [<CommonParameters>]

 

Get-WinEvent [-Path] <string[]> [-MaxEvents <long>] [-Credential <pscredential>] [-FilterXPath

<string>] [-Oldest] [<CommonParameters>]

 

Get-WinEvent [-FilterXml] <xml> [-MaxEvents <long>] [-ComputerName <string>] [-Credential

<pscredential>] [-Oldest] [<CommonParameters>]

 

Get-WinEvent [-FilterHashtable] <hashtable[]> [-MaxEvents <long>] [-ComputerName <string>]

[-Credential <pscredential>] [-Force] [-Oldest] [<CommonParameters>]

From this, there are basically three ways of filtering:

  • Via XML
  • Via a hash table
  • Via XPath

Dude!!!

The easy way to an XPath query

Believe it or not, the easy way to filter the results of Get-WinEvent is with XPath. This is because I can use the Event Viewer to create my query for me. To do this, I open the Event Viewer, right-click the log, and choose Filter Current Log from the action menu. I then use the check boxes, drop-down lists, and text boxes to filter the content of the selected log. This is shown in the following image:

Image of menu

I then click the XML tab to look at the query. This is shown here:

Image of menu

Now I select the Edit query manually check box. This permits me to highlight the query. I always copy the query and paste it into Notepad. When I have the query in Notepad, I select the Path portion of the query:

Image of command

I open the Windows PowerShell ISE, create my query, and add a line for my Get-WinEvent cmdlet:

$xpath = "*[System[(Level=2) and (EventID=35)]]"

Get-WinEvent -LogName application -FilterXPath $xpath 

And that is the easy way to query a log by using the Get-WinEvent cmdlet.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Use PowerShell to Read the Content of a ZIP File

$
0
0

Summary: Learn how to use Windows PowerShell to read the content of a .zip file.

Hey, Scripting Guy! Question How can I read the content of a .zip file from within Windows PowerShell?

 Hey, Scripting Guy! Answer Use the OpenRead static method from the IO.Compression.ZipFile .NET Framework class.
            First, you will need to load the assembly that contains the class. Here is an example:

Add-Type -assembly "system.io.compression.filesystem"

[io.compression.zipfile]::OpenRead("E:\Ch10.zip").Entries.Name

Weekend Scripter: Use PowerShell to Create Folder

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to create folders.

Microsoft Scripting Guy, Ed Wilson, is here. I am not a huge fan of using a mouse. In fact, the more things I can do from Windows PowerShell the better. It is a huge waste of time for me when I have to remove my hands from the keyboard, chase down a mouse, mouse around for a while, and then return my fingers to the home row on the keyboard. One cool thing is that Microsoft Word has a number of keyboard shortcuts—of course, it also has an API. I also do quite a bit of scripting for that.

Another place where I use Windows PowerShell quite a bit is for creating folders, directories, or containers (whatever we are calling them this week). I know that Windows creates lots of default folders, but they seem to be buried in my profile, and they are not all that accessible. I prefer to create my own directory structure to make it easier to copy, back up, and to use from within a Windows PowerShell script or console.

Something I often see is that scripters test for the existence of a folder, then if the folder does not exist, they create it. Here is a typical form of this code:

$path = "c:\fso"

If (Test-Path -Path $path -PathType Container)

    { Write-Host "$path already exists" -ForegroundColor Red}

    ELSE

        { New-Item -Path $path  -ItemType directory }

Although the previous code works, it is an awful lot of work. One might decide to add this as an ISE script snippet to simplify the coding process.

But what is the purpose of the code? Most of the time, the purpose is to avoid an error message that occurs when creating a folder that already exists. If this is the purpose of writing such code, you can avoid the error message by using the –Force parameter. Here is an example:

New-Item -Path c:\fso1  -ItemType directory -Force

In the following image, I run this command twice. Note that no error occurs.

Image of command output

I can use the New-Item cmdlet to create a nested folder—even if the root folders do not exist. This is shown here:

$path = "c:\fso3\fso3\fso3\fso3"

Remove-Item $path -Recurse -Force

New-Item -Path $path  -ItemType directory -Force

My favorite way to create a new folder is to use the MKDIR function (MD is an alias for MKDIR). MKDIR is cool because it already knows that I want to make a folder, and so I can skip that parameter. I can also specify an array of folder names in the function. I can specify the –Force parameter to keep the command from generating errors if a folder already exists. Here is an example:

$path = "C:\fso","C:\fso1","C:\fso2"

md $path -Force

The command and its output are shown here:

Image of command output

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Find if Folder Exists

$
0
0

Summary: Use Windows PowerShell to see if a folder exists.

Hey, Scripting Guy! Question How can I easily find if a folder exists for a Windows PowerShell script that I am writing?

Hey, Scripting Guy! Answer Use the Test-Path cmdlet and the PathType parameter, for example:

Test-Path c:\fso -PathType Container

Use PowerShell to Create ZIP Archive of Folder

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to create a .zip archive of a folder.

Hey, Scripting Guy! Question Hey, Scripting Guy! I need a way to create a .zip archive of a folder. I would like to do this on my laptop running Windows 8.1, and I do not want to install any other software. Can I do this?

—TR

Hey, Scripting Guy! Answer Hello TR,

Microsoft Scripting Guy, Ed Wilson, is here. The weed eater dude is outside. The guy is really dedicated to his job. I mean, the snow has barely cleared, and he is out there chopping away with his weed eater. I really enjoy hearing him, because it fills me with hope that summer is on its way, and that soon we will have warm weather and we can get outside without having to bundle up.

Certainly I can put on a coat and hop on my bicycle, but I learned (the hard way) a long time ago that trying to ride a bicycle when there is ice on the road is not the smartest thing to do (at least not for me). So I prefer to wait until the snow melts, the ice thaws, and the sun is out before taking to the open road.

TR, luckily, you do not need to wait for anything before you can use Windows PowerShell to create a .zip archive. You have everything you need—and that is .NET Framework 4.5.

The ZipFile .NET Framework class was introduced with .NET Framework 4.5, and Windows 8.1 ships with .NET Framework 4.5 installed. This is really cool because this class is extremely easy to use.

The ZipFile class is not available by default in Windows PowerShell because the System.IO.Compression.FileSystem assembly is not loaded by default. Therefore, I want to load the assembly. The best way to do this is to use the Add-Type cmdlet and specify the name of the assembly as an argument to the –Assembly parameter. This is the command:

Add-Type -assembly "system.io.compression.filesystem"

The ZipFile .NET Framework class has a static method named CreateFromDirectory. This method accepts two arguments: a source directory and a destination file. The source directory and the destination file cannot reside in the same directory. This is due to file locking, and it will generate the following  error message:

Image of error message

When you are using this method, if the file archive file already exists, the following error message appears:

Image of error message

To fix this issue, I add a Test-Path command to delete the archive file if it already exists. This is shown here:

If(Test-path $destination) {Remove-item $destination}

The CreateFromDirectory method is easy to use. It is a static method, so I can access it directly from the ZipFile class. Also it takes two arguments, Source and Destination, so the method call makes sense. Here is the command I use:

[io.compression.zipfile]::CreateFromDirectory($Source, $destination)

For the complete script, I add Source and Destination as variables at the beginning of the script. Remember, Source is a directory and Destination is a file that will hold my .zip archive. Here is the complete script:

$source = "C:\fso"

$destination = "C:\fso1\FSO_Backup.zip"

 If(Test-path $destination) {Remove-item $destination}

Add-Type -assembly "system.io.compression.filesystem"

[io.compression.zipfile]::CreateFromDirectory($Source, $destination) 

Now when I run the script, an archive appears in my destination folder. The archive contains all of the files from the source. This is shown here:

Image of folder

TR, that is all there is to using Windows PowerShell to create a .zip archive of a folder. ZIP Week will continue tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 


PowerTip: Use PowerShell to Find ODBC Drivers

$
0
0

Summary: Use Windows PowerShell to find installed ODBC drivers.

Hey, Scripting Guy! Question How can  I use Windows PowerShell to check installed ODBC drivers so that I can investigate if a missing
           driver might be the cause of a database application that appears to be failing?

Hey, Scripting Guy! Answer Use the Get-OdbcDriver function from the WDAC module, for example:

Get-OdbcDriver | Format-Table name, platform -AutoSize

Use PowerShell to Zip Multiple Folders

$
0
0

Summary: Use Windows PowerShell to create a .zip archive of multiple folders.

Hey, Scripting Guy! Question Hey, Scripting Guy! I need to compress multiple folders before I attempt to archive them. I would like to do this without having to install additional software. Can you help?

—DR

Hey, Scripting Guy! Answer Hello DR,

Microsoft Scripting Guy, Ed Wilson, is here. This afternoon I am sipping a red berry tea and munching on a chocolate biscotti. Maybe it is not too exciting, but it is relaxing. I am looking over my email sent to scripter@microsoft.com on my Surface 3 Pro, and things are good.

One of the cool things about the free update to Windows 8.1 from Windows 8 is that in addition to including Windows PowerShell 4.0, it includes .NET Framework 4.5, which is way cool. The thing I love the best is the improved compression classes. It makes working with .zip files a piece of cake.

I have a folder on my laptop that I use for backing up files, creating archives, and stuff like that. So, I do not need to check to see if a folder exists or worry about overwriting such a folder. Here is the path assignment in my script:

$path = "C:\backup"

I use the Get-ChildItem cmdlet to find all of the folders I want to archive. In this example, I want to archive all of my FSO* types of folders. I test my command before I add it to my script. This is the command and its output:

PS C:\> Get-ChildItem -Path c:\ -Filter "fso?" -Directory

    Directory: C:\

Mode                LastWriteTime     Length Name                                      

----                -------------     ------ ----                                      

d----          3/4/2015   9:47 AM            fso                                        

d----          3/9/2015   3:28 PM            fso1                                      

d----          3/9/2015   3:28 PM            fso2                                      

d----          3/9/2015   3:28 PM            fso3       

The cool thing is that in the Windows PowerShell ISE, I can highlight only the portion of the command I want to use, and that is what runs. So my actual command will be:

$source = Get-ChildItem -Path c:\ -Filter "fso?" -Directory

I know that this returns a DirectoryInfo object, and that I need to access specific properties to get to the individual folder paths—but I will do that later.

I need to add the assembly that contains the compress classes, so I do this here:

Add-Type -assembly "system.io.compression.filesystem"

I now need to create the destination path for each archive I will create. I do this inside a loop that walks through my collection of DirectoryInfo objects. This script is shown here:

Foreach ($s in $source)

 {

  $destination = Join-path -path $path -ChildPath "$($s.name).zip"

I keep only one archive of a folder in my Backup folder at a time, so if the archive exists, I want to delete it. Here is the script that accomplishes that task:

If(Test-path $destination) {Remove-item $destination}

Now it is the simple task of creating the archive. Here is the command:

[io.compression.zipfile]::CreateFromDirectory($s.fullname, $destination)

The complete script is shown here:

$path = "C:\backup"

$source = Get-ChildItem -Path c:\ -Filter "fso?" -Directory

Add-Type -assembly "system.io.compression.filesystem"

Foreach ($s in $source)

 {

  $destination = Join-path -path $path -ChildPath "$($s.name).zip"

  If(Test-path $destination) {Remove-item $destination}

  [io.compression.zipfile]::CreateFromDirectory($s.fullname, $destination)}

I check to see if the archives exist. As shown in the following image, they do:

Image of folder

DR, that is all there is to using Windows PowerShell to create a .zip archive of multiple folders. Zip Week will continue tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Use PowerShell to Map a Drive

$
0
0

Summary: Learn how to use Windows PowerShell to map a drive.

Hey, Scripting Guy! Question How can I use Windows PowerShell  to map a drive to a server from a client running Windows 8.1?

Hey, Scripting Guy! Answer Use the New-SmbMapping cmdlet and specify the local path and the remote path, for example:

New-SmbMapping -LocalPath h: -RemotePath \\dc1\Share

Use PowerShell to Extract Zipped Files

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to extract zipped files.

Hey, Scripting Guy! Question Hey, Scripting Guy! I need to be able to work with zipped files from time-to-time. Often I store files in a zip archive so they are portable. I know how to copy the .zip archive from one place to another with Windows PowerShell, but I cannot seem to figure out how to unzip the archive. Can you help me? I would be ever so grateful.

—SK

Hey, Scripting Guy! Answer Hello SK,

Microsoft Scripting Guy, Ed Wilson, is here. This morning I got out my bag of expresso beans and set up my rotary bean grinder. I am thinking I will make some expresso this afternoon…or maybe tomorrow afternoon. I have an old-fashioned, stovetop, double-boiler. It is like one I bought a long time ago when I was in Naples, Italy. It is ridiculously simple, and does an excellent job. I put the water in the bottom and super finely ground beans in the middle, and after a short time, the expresso appears in the top. The only trick is ensuring that I get the right amount of water in the bottom.

I sometimes also make cappuccinos on Saturday mornings, and I have a hand milk frothier that I use for that. I love using manual tools when I have time, or when I want to take time for an exceptional occurrence. However, for things that occur more than once or twice a month, I want to automate them—big time. Maybe one day, someone will invent a PowerShell powered teapot.

To extract all files from a .zip archive file, I use the ExtractToDirectory static method from the [io.compression.zipfile] .NET Framework class. To use this class, I need to add the System.IO.Compression.FileSystem assembly to my Windows PowerShell console or to the Windows PowerShell ISE.

To add the assembly, I use the Add-Type cmdlet and specify the –Assembly parameter. This command is shown here:

Add-Type -assembly "system.io.compression.filesystem"

The command to extract the zipped files to a folder is:

[io.compression.zipfile]::ExtractToDirectory($BackUpPath, $destination)

Here are a few things to keep in mind:

  1. The first parameter I call ($BackUpPath)must point to a specific zipped file.
  2. The second parameter (the one I call $destination) must point to a folder.
  3. Both of these parameters are strings. Therefore, I cannot use a ziparchive object or a directoryinfo object as input types.
  4. The extraction does not include the root folder.

My complete script is shown here:

$BackUpPath = "C:\backup\fso.zip"

$Destination = "C:\recovered"

Add-Type -assembly "system.io.compression.filesystem"

[io.compression.zipfile]::ExtractToDirectory($BackUpPath, $destination)

When I go to my C:\recovered folder, I see that all of the files from the fso.zip folder are now present.

SK, that is all there is to using Windows PowerShell to extract zipped files. Zip Week will continue tomorrow when I will talk about zipping and emailing an archived folder.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Use PowerShell to Copy Source to Multiple Destinations

$
0
0

Summary: Use Windows PowerShell to copy a source directory to multiple destinations.

Hey, Scripting Guy! Question How can I use Windows PowerShell to make multiple backup copies of a source directory without wasting a
           lot of time mousing around?

Hey, Scripting Guy! Answer Copying a single source directory to multiple destinations can be a single line command, for example:

"c:\fso1","c:\fso2","c:\fso3" | % {Copy-Item c:\fso -Recurse -Destination $_}

Note  The % symbol is an alias for the Foreach-Object cmdlet.

Viewing all 3333 articles
Browse latest View live




Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>
<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596344.js" async> </script>