Quantcast
Channel: PowerShell General
Viewing all 10624 articles
Browse latest View live

Module confusion–what’s really in PowerShell 3 and 4

$
0
0

If I run

Get-Module –ListAvailable

on my Windows 8.1 system (PowerShell 4.0) I find a total of 58 modules installed in $pshome\modules i.e. C:\windows\system32\WindowsPowerShell\v1.0\Modules

These are the modules installed as part of PowerShell. Right?

Wrong?

Read More


Windows PowerShell Operators

$
0
0

Windows PowerShell is designed to be an interactive command-line shell, but it's also a programming language. As you advance in your PowerShell understanding and knowledge, it's inevitable you're going to run into a number of core computer programming concepts. Operators are one of these core programming concepts, and you've probably already been using them without necessarily knowing everything about them.

Read More

Handling Errors in PowerShell

$
0
0

As DBAs, we're always working on protecting ourselves from problems by disaster recovery procedures like backups, but in our haste to get a script done, we also are prone to forget the same concept within our code to protect the process from errors.

Read More

PowerShell –EncodedCommand and Round-Trips

$
0
0

PowerShell.exe accepts the –EncodedCommand parameter, which is a way to ‘wrap’ DOS-unfriendly command strings in such a way as to be safely passed into PSH for execution.  It’s a great feature.  However, it has a huge documentation hole.  Let’s see what PowerShell.exe /? has to say about it:

Read More

Breaking Down PowerShell's Scope

$
0
0

One constant about PowerShell is that someone is always learning it. So I shouldn't be too surprised to get e-mails or tweets about beginner topics. It helps remind me that Prof. PowerShell needs to revisit some key concepts from time to time. One such topic is scope.

Read More

Windows PowerShell Operators

$
0
0

As you advance in your PowerShell understanding and knowledge, it's inevitable you're going to run into a number of core computer programming concepts. Operators are one of these core programming concepts, and you've probably already been using them without necessarily knowing everything about them.

Read More

Windows Management Framework 5.0 Preview Introduces PowerShell 5.0

$
0
0

As if you needed more to this month with Patch Tuesday imminent, Windows XP and Office 2003 expiring, and Windows 8.1 Update 1 and Windows Server 2012 R2 Update on the way, Microsoft has made available the preview download for the Windows Management Framework 5.0. WMF 5.0 introduces some updated components, as well as, some new ones.

Read More

WinRT and PowerShell Part 1

$
0
0

This is a post about using Windows Runtime (WinRT) components “projections” from PowerShell.

Read More


List compile errors using PowerShell

$
0
0

 I always make sure that any compilations are logged. You do this by opening Tools, Options, Development, Compiler and check the "AOT log"-checkbox.

Read More

Locate machines where a specific account is present

$
0
0

I need to find all machines where there is a local account named, say, 'John' and include its group memberships (specifically if the account is a member of Administrators and/or another group we created).  I also need to know if the account's password is set to never expire.

 

Can this be done through WMI, or do I need to use the [ADSI]"WinNT" provider?

 

Should I use gwmi Win32_Useraccount and filter on the name, then pipe that to something else?

What I'm looking to get back is a list of machines where the account exists, and the account's properties and group memberships.  Returning a boolean for the group membership is what I was thinking, giving a returned record similar to:

 

Computername,User,IsAdmin,IsAuditor,PwdExpires,Disabled

Computer1,John,True,False,False,False

 

Thanks for any help,

 

J

Outlook 2013 Calendar appointment with invitation.

$
0
0

Hi all,

I have a ps script that i am attempting to use to automatically set appointments through outlook 2013 that is an exchange account. Everything works except i cant seem to figure out how to send an invitation to an email address, or a group of email address (this will be different as the PS script is embedded into an automation program to open up powershell and run the script using variables for the calendar information.) anyone have any idea how to send the appointment as a invitation? i was able to send it as a internet calendar but that is it.

 

Just so people are aware of where i am at now, the ps script is below. Using this script is all contingent on getting the ability to send email invitations per calendar meeting.

 

Add-Type -AssemblyName microsoft.office.interop.outlook 

$olFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]

$olCalendarDetail = "Microsoft.Office.Interop.Outlook.olCalendarDetail" -as [type]

$olCalendarMailFormat = "Microsoft.Office.Interop.Outlook.olCalendarMailFormat" -as [type]

$outlook = New-Object -ComObject outlook.application

$namespace  = $Outlook.GetNameSpace("mapi")

$folder = $namespace.getDefaultFolder($olFolders::olFolderCalendar)

$CalendarSharing=$folder.GetCalendarExporter()

$CalendarSharing.CalendarDetail = $olCalendarDetail::olFreeBusyOnly

$CalendarSharing.startDate = Get-Date

$CalendarSharing.endDate = (Get-Date).addDays(7)

$CalendarSharing.RestrictToWorkingHours = $true

$CalendarSharing.IncludeAttachments = $false

$CalendarSharing.IncludePrivateDetails = $false

$MailItem = $CalendarSharing.ForwardAsICal($olCalendarMailFormat::olCalendarMailFormatDailySchedule)

$MailItem.Recipients.Add("Example.Email@anyone.com")

$MailItem.Send()

Building Excel Spreadsheet - From Inside Powershell Script

$
0
0

Greetings,

Let me preface this post by stating I am a noob to powershell.  I am still in the very beginning phases of learning.  Thus far I have been able to pull down scripts, piece them together, and compile them (after many hours).  Please keep in mind the scripts have been very entry level. 

It was suggested that I create a new topic, and link the previous post I appended my question to, so here it is: (http://powershell.com/cs/forums/t/13296.aspx). 

With that said, here is what I would like to do.  I have many scripts I have pieced together that all primarily pull data from a text file, and output that data to excel or to a text file.  I chose a simple script from the link I mentioned above, only as a reference as it appears to be a relatively simple script.  Rather then have the data outputted to an excel file at the end, I would like to learn how to achieve the same thing, however have the script launch Excel, and begin filling in the data as I watch.

Not that it matters, however, I would like to do this so I can visibly see how far along the script is coming along.  I currently have a script that does this successfully, but since I am still learning powershell, and working with variables etc.. I was hoping somebody could help me, since I haven't had much luck.

Here is the script that I took from the link I posted above, please note that I understand that the export-csv line towards the end wouldn't be needed, since we'd be building a new sheet (I believe):

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

Get-Content .\Servers.txt | ForEach-Object {
    if(Test-Connection -ComputerName $_ -Quiet -Count 1) {
        New-Object -TypeName PSCustomObject -Property @{
            VMName = $_
            'Ping Status' = 'Ok'
        }
    } else {
        New-Object -TypeName PSCustomObject -Property @{
            VMName = $_
            'Ping Status' = 'Failed'
        }
    }
} | Export-Csv -Path Results.csv -NoTypeInformation

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

Here is what I believe needs to happen first to launch Excel, and build out the worksheet etc.. however I don't know how to actually get the script to fill in the cells. I am not at all partial on if this is csv or excel format etc.. I can alway's pull the data out myself, or learn more about that at a later time.

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

$excel = new-object -comobject Excel.Application
$excel.visible = $true

$workbook = $excel.workbooks.add()
$worksheet = $workbook.ActiveSheet

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

As you can tell, I'm not really sure what I'm doing here, and would appreciate any assistance.  Again, using this script as an example, I would like to pull specific servers from a text file (already setup) and ping each of them to determine their up-time.  While this is occurring, I would like to be able to watch the data populate into the spreadsheet.

I apologize for any dumb questions, and appreciate your patience with me.  Thanks for your help, and time.

Can you explain this hashtable?

$
0
0

Hi,

I understand the basic principle of powershell hashtables but there are elements of this one that I was hoping you can explain;

@{name="MemberOf";expression={$_.memberof -join "`n"}}

I don’t understand what the –join operator is used for and what "`n" is?

The full command;

$Users = get-aduser -filter *  -SearchBase 'ou=users,dc=mydomain,dc=local' -properties memberof

 

$Users.MemberOf.ToString()

 

$Users | Select-Object GivenName,Surname,SamAccountName,@{name="MemberOf";expression={$_.memberof -join "`n"}} |Export-CSV c:\temp\MemberOf.csv -NoTypeInformation

 Thanks.

 

Switch parameter, Change/Set words

$
0
0

In my script, I extract a word in 3rd position, from a path.

I then need to insert this word in a text, such as

Add-Content -Path $sFullPath -Value "NFSettingFile=C:\NG_auto_project\config\$word.ini"

BUT if that word matches certain characters/words it should write 'default'. I worked it out with an IF statement but saw that Microsoft says that with lots of conditions it's better to use the switch parameter. In either way, the following script doesn't work as I expect:

switch($Word)
{
    {$_ -eq "ODDX"} {"default"}
    {$_ -eq "ODCL"} {"default"}
    {$_ -eq "CRC"} {"default"}
    {$_ -eq "CPKRAS"} {"default"}
    {$_ -eq "OTDX"} {"default"}
    {$_ -eq "ODTRC"} {"default"}
}

The problems is that it changes everything unto 'default' and that's not what I want. I only need to have the words change to default IF they do not match one of these characters.

Do you see what I'm doing wrong?

add-type fails to load an assembly, but why?

$
0
0

I am trying to call method Path.GetFileNameWithoutExtension ( ie - [Path]::GetFileNameWithoutExtension( ... ) ).

However, Powershell reports that the assembly containing the type is not loaded: 'Unable to find type [Path]: make sure that the assembly containing this type is loaded.'

So I try to load the assembly containing the Path class (according to msdn, the Path is in the System.IO namespace, but in the mscorlib.dll assembly). I attempt to load the assembly as follows:

add-type -AssemblyName "mscorlib"

Nothing is returned so I retry my method call again, but the same error is reported:

Unable to find type [Path]: make sure that the assembly containing this type is loaded.

So, what am I doing wrong? This is quite confusing because when you search for this error, the fix is to use add-type, but the examples quoted look like they've specified a namespace, not an assembly.

PS, I'm doing this all in a powershell console interactively.

Appreciate a fix to this silly problem, thanks.

 


compare variable to object in array

$
0
0

Hello

i am trying to get my script working but i am having some problem.

I have a script that allows me to enter a string in a popup window.

What i am trying to do is to get that string that has been entered into a variable and to compare it to an object from array and if it is equal to it to create a file with matched string.

Here is what i have:

 

$serverLogfolder = (gci "D:\!Joro\Powershell\" | where-object { $_.PSIsContainer} | sort CreationTime -desc | select -f 1 | Foreach-Object { $_.FullName })
 
$Errorfile = ""
#$Dbmodulefile = @(Get-ChildItem (join-path $serverLogFolder $serverLogfile) -Filter *.txt | ForEach-Object{'{0,-20}{1,10}' -f $_.Name,(Get-Content $_).Count })
#$Errorreport_file = @(Get-ChildItem $errorfile -Filter *.txt | ForEach-Object{'{0,-20}{1,10}' -f $_.Name,(Get-Content $_).Count })
$LogfilesAray = @("a.xt", "b.txt", "c.txt")
$ErrorfilesAray = @("a_error.txt", "b_error.txt", "c_error.txt")



[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Data Entry Form"
$objForm.Size = New-Object System.Drawing.Size(300,200)
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
    {$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
    {$objForm.Close()}})

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = "Please enter the information in the space below:"
$objForm.Controls.Add($objLabel)

$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(10,40)
$objTextBox.Size = New-Object System.Drawing.Size(260,20)
$objForm.Controls.Add($objTextBox)

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

$x


    if ( $x  -eq $LogfilesAray[0])
    {
        $errorfile == ErrorfilesAray[0]write-host "True"
    }
}
(Get-Content (join-path $serverLogfolder $serverLogfile) | Where-Object {$_.StartsWith((Get-Date).AddDays(-1).ToString("yyyyMMdd"))}  | select-string -notmatch "Network Error" | out-file "D:\Powershell\errorfiles\"$Errorfile)

 

This is what i am trying but i am getting error:

out-file: cannot validate argument on parameter 'encoding'. The argument "" doesn not belong yo the set "unicode, utf7,utf8,utf32" specified by the ValidateSet attribute.Supply the argument that is in the set

Is it possible to have variable with empty string like: $Errorfile = ""

and to assign it the result after i compare input variable to the array object.

Can any one help me with this :)

 

 

 

best way to Copy file on a remote computer

$
0
0

This should be simple, but i'm new to PS.  What is the best way to copy files on a remote computer?  

I will be running the script from ComputerA, and it will copy a File from C:\FolderA to C:\FolderB, both on ComputerB.  I don't need anything transferred over the network.

 

Thanks

 

New-Item change Get-Date format

$
0
0


I have problem with Get-Date and New-Item:

example nr 1:
-------------------
$today = Get-Date
echo $today
-------------------
---> show date format: 7 kwietnia 2014 10:45:11

example nr 2:
-------------------
$today = Get-Date
New-Item -ItemType file -Path C:\test.txt -Force -value $today
echo $today
-------------------

---> show date format:

DisplayHint : DateTime
Date        : 2014-04-07 00:00:00
Day         : 7
DayOfWeek   : Monday
DayOfYear   : 97
Hour        : 10
Kind        : Local
Millisecond : 104
Minute      : 48
Month       : 4
Second      : 36
Ticks       : 635324645161046371
TimeOfDay   : 10:48:36.1046371
Year        : 2014
DateTime    : 7 kwietnia 2014 10:48:36

---> file c:\test.txt contain date format:
2014-04-07 10:48:36

One date variable, three different date formats.

Why New-Item change date format?

Modifying properties of Recycle Bin with Powershell

$
0
0

Hi Everyone,

I am trying to create a script to modify the properties of the Recycle Bin. For instance on some drives I want to change it so it doesn't go to recycle bin while on other drives I want to change it to a prompt delete confirmation.  I am not able to find a way to do that. Any help would be greatly appreciatedl


Thanks

Nate

Disable services across several servers - found post by Martin, need help :)

$
0
0

Hey Everyone

I'm one of the newbies here and I am trying to disable several services on several servers remotely.

I found a post by Martin but I wanted to post here so that I can use 1 forum.

Here was the answer Martin suggested and it worked for the user, but I can't get it to work.  There are a couple of services that have a !Space! in the name, but I tried with services that do not. I also want to stop the service and disable it.  This doesn't do that.  Can anyone help?

1. Create a CSV like this

ComputerName,Service
Server1,"service1,service2,service3"
server2,"service4,service5,service6"
2.  Use this code:
$List=Import-CSVc:\scripts\servers.csvForEach($Serverin$List){Invoke-Command-ScriptBlock{Stop-Service$args[0]}-ComputerName$Server.ComputerName-ArgumentList$Server.Service.Split(",")}Start-Sleep-Seconds60ForEach($Indexin(($List.Count-1)..0)){Invoke-Command-ScriptBlock{Stop-Service$args[0]}-ComputerName$List[$Index].ComputerName-ArgumentList$List[$Index].Service.Split(",")
Viewing all 10624 articles
Browse latest View live