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

Browse to a directory and assign to a variable

$
0
0

I would like to be able to browse to a local directory and then assign the path to a variable.

Ideally it would be by using the windows browse function or something similar.

I would imagine this would be fairly easy to achieve.

I'm still fairly new to PS and am finding myself lost and confused a lot of the time.

 

Ray

 


Call Powershell script from VBA using Shell() function

$
0
0

Hello,

I'm trying to pull a path string variable from the following VBA code into a PS script:

:VBA CODE:

Shell("powershell.exe -ExecutionPolicy Unrestricted -File <pathname>\Convert_To_Tab_Delimited.ps1 -path """& pathVariable &"""",1)

:END OF VBA CODE:

I then have the string variable parameter set as a param in the PS script:

:PS CODE:

param([String]$FileToOpen)

gc $FileToOpen| % { $_ -replace '  +',"`t" } | set-content "<my path>\temp.txt"

:END OF PS CODE:

I am using full paths outside of the path variable.  Does anyone have any ideas?

RSS -> Out-GridView as text

$
0
0

This works perfectly.

$url='http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml'
$wc = New-Object Net.WebClient
[xml]$resp = $wc.DownloadString($url)
$resp.rss.channel.item |Select Link,Description |Out-Gridview -Title "NY TIMES RSS"

but I would like the Link and Description columns in the Gridview to be plain text, and is it possible to wrap a column in the Gridview.

still learning....

 

Building up Hash Tables avoiding key name conflicts

$
0
0

Hello All

Can someone please assist me with the following question :)
In the past when creating hash tables I have mistakenly specified the same key name and therefore get an error saying that key name already exists in the hash table. Therefore I was trying to think of a way to take data from a pipeline with may contain duplicate values and create a hash table but automatically skip duplicates as they arise (using PosH 2 at the moment)

I came up with the following solution (do not worry about the values at this time, just keeping it simply and thinking about the keys)

My question is, is there an easier/more elegant way to achieve this, 

Thanks all

Ernie

cls
$HT= @{"John Smith"= 0;"Jane Brown"= 0}
$X="Ernest Brant","Bert Jackson","Jack Brown","Jane Brown","Ernest Brant","Bert Jackson"

foreach ($elementin$X)

{

if (($HT.Keys | % {$_.ToString()}) -match$element) {continue} else

{$HT.Add($element,0)}


}

$HT

Add JPG to form

$
0
0

Hi,

here is a basic form code :

Add-Type -AssemblyName System.Windows.Forms

$Label = New-Object System.Windows.Forms.Label

$Form = New-Object system.Windows.Forms.Form

$Form.Text="Date"

$Form.AutoSize = $True

$Form.MinimizeBox = $False

$Form.MaximizeBox = $False

$Form.WindowState = "Normal"

$Form.StartPosition = "CenterScreen"

 

$Form.ShowDialog()

how can I add a JPG\ICO to the form? and how determine his size and location on the form?
Thanks
Lior

Powershell executing a background job

$
0
0

I am trying to execute a powershell command in  my local computer using the below command. I log in to powershell and then execute the below command to execute a cmd script in the background , in my local computer. It works.

invoke-command -computername mycomputername -scriptblock{ C:\Data\test.cmd} -AsJob

Now if don't login in to powershell but from my normal command prompt if i execute the same command by passing the invoke command as a parameter to the powershell.exe, the script is not executed.

c:\Users\myusername>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  

invoke-command -computername mycomputername -scriptblock{ C:\Data\test.cmd} -AsJob

If i remove the -AsJob from the above command, then i am able to execute the script. Can i not use the above command to execute a script in background by passing it as a parameter to the powershell.exe process. I need this because in my external application i have to call powershell using the C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  command.Am I missing anything? Any help is appreciated

Get-ChildItem to get directories and files.

$
0
0

I want to use Get-ChildItem to get the directories and files into one object. Normally this command will return two objects, directory and file. I would like to get each file and know what directory it was in. This would then be an object I could enumerate thru.

Thank you,

Goo

Cool RegEx Tip, replace text and count replacements in on go

$
0
0

Hello All

I was playing around with RegEx again today (yes I really do need to get out more), and wounded if I could replace text and count the replacements at the same time

Therefore I was looking at some of the overloads available on [regex]::Replace static method

I see it has a "MatchEvaluator Delegate" which basically runs some logic returns the result and the result is used for the replacement. more information here 

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx

So, I came up with the following, which basically does the replacement and tells you now may times the replacement took place. Hope this is helpful, perhaps we can write this up and send it out as a tip from this site? of course the could run other code in the script block.

 

cls
$i= 0
$String="AABBAASSAA"
$Pattern="AA"
[scriptblock]$Eval= {$i++;write-output"TT"}
[regex]::Replace($String,$Pattern,$Eval)
$i

Using variables

$
0
0

Hi,

 

I run a code that have form with button, when I press the button I'm doing operations in variables,

I want to use those variables after I use the button, for example:

1. ..........

2. ..........

3. .........

4. $button.add_Click(

{

      $UserName="Danny"

      $UserQuotas=Get-Mailbox $UserName

 

}

)

5. doing operations on $UserQuotas

 

I get nothing when I'm doing operations on $UserQuotas (5)

how can I get the value out of the button "loop"?

 

thanks

Lior

 

 

 

RegEx Tip, Replace String set number of times

$
0
0

All

Here is another quick tip, last one Smile

lets say you have a string "AA124BB55HH657AAR555" now you want to replace the numbers (but only where there are 3 numbers together, not just 2) with say a # symbol, but you only want to replace the first two instances of 3 numbers. You will see this string contains three sets of three numbers

[regex]'\d{3}').Replace('AA124BB55HH657AAR555','#',2)

AA#BB55HH#AAR555

Hope this is helpful

Ernie

Powershell & .ZIP Files

$
0
0

Hello,

Is there a way in powershell to get the uncompressed sizes and names of files within a .ZIP file?

Any help would be most appreciated,

Andrew

Getting Powershell to request information for variables.

$
0
0

I currently have a Powershell script that I use for creating Users in Active Directory.  I mainly use it for batch jobs when customers want to add 5 or more users..   It works perfectly for this as I simply have to type in the Script name and the name of the csv file that has the list of users in it.  

What I would like to also be able to do is execute the script without a csv file name and then have the script ask me a number of questions.  IE, User First name, Last name, UserID, password, and email.  All things I already have in the csv file format..  

Could someone point me in the right direction that helps explain how this can be done in Powershell?  I know I could plug this information into paramaters and input it as part of the command line, but I'd really like to be able to give this to some of my customer admins so they can add users themselves.  So it needs to be pretty simple and straight forward.. 

 

problem with variables input

$
0
0

Hi,

I build a form that the user write a number in the windows, when he click the button, this value

is the new prohibit Send quota in the MailBox.

part of the script:

$ChangeButton.add_click(

{

[int]$NewProSendQuota=$prohibitSendquotaValue.Text

Set-Mailbox $UserName -ProhibitSendQuota $NewProSendQuota

})

the problem is that if i type in the window 5000 the command Set-Mailbox see it like that: 5000B

and I get an error:

"... The value of property 'ProhibitSendQuota' must be greater than or equal to that of property 'IssueWarningQuota'. ProhibitSendQuota: '50000B', IssueWarningQuota: '4400KB'."

 

I think he show the value in bites, how I can define the variable $NewProSendQuota that the input is in KB?

 

Thanks

Lior

 

 

test-connection

$
0
0

Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4

don - in your Month of Lunches book chapter 9.8 you have ideas for on your own and ask:

Or use Test-Connection to ping several

computers, and only show the results from computers that did not respond

 

I tried several things then did what I do best and stole a cmd and came up with this (I am sure you know where I stole it from…J)

get-content c:\hold\machines.txt | foreach { if (test-connection $_ -quiet) { $null } else {write-host "$_ is down" -foregroundcolor RED}}

 

Now I get the desired results but my question is :       how does it know if it’s up or down?  All I did was run a test-connection and then a write-host.   I didn’t call for anything like statuscode or timeout and say if statuscode is X  then …….

Also if I ping a computer (who is in dns but not up) I get request timed out…..but test-connection gives me:

Test-Connection : Testing connection to computer 'XXXX' failed: The requested name is valid, but no data of the requested type was found At line:1 char:16 + test-connection <<<<  XXXX    + CategoryInfo          : ResourceUnavailable: (XXXX:String) [Test-Connection], PingException     + FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand

Getting information from .zip files

$
0
0

Hello,

Is there a way of using powershell to get information from files that are in a .zip folder (specifically, filename and uncompressed size)?

Any help would be most appreciated,

Regards,

Andrew


Help with a powershell script to use a parameter to manipulate/read in fields in another csv file

$
0
0

Hi Guys, 

I am powershell novice so asking for assistance for what is to me  a difficult problem but hopefully a quite easy solution to PS experts!!. 

I have and existing powershell script (not written by me!!) which is designed to use a passed in Parameter (SCOM Alert ID) to then set additional information in the alert, eg $alert.CustomField1 = $alert.PrincipleName etc etc.

I am looking to add functionality to this script to be able to add additional 'Custom' information which is stored in a separate text/csv file.  The text/csv file has header line ServerName,ServiceOwner,Application Tier so a row in the file would be MYSERVER.CONTOSO.COM,Joe Bloggs, Tier 1 - there will be one unique row for each server in our environment (over 600 rows)

So what I need to do is using the passed in alertID I can use $alert.PrincipleName to find the corresponding row in the text file and pull in the additional details stored in field 2 and 3 ie ServiceOwner and ApplicationTier.  This logic holds for the majority of alerts but IF server name is a specific value (eg MYSTSERVER.CONTOSO.COM) then instead of using $alert.PrincipleName to match servername in text file, I need to match on another alert property $Alert.MonitoringObjectDisplayName - but the server name in this field is part of a larger string in the format eg: User Services Watcher for Pool [MYTARGETSERVER.CONTOSO.COM] - so I need to extract the severname from between the square brackets  of the string to then perform the match with the text file.

Hopefully I have explained what I'm trying to do clearly - if not I'm happy to provide further clarification and can also post up the existing PS Script I'm trying to modify if thats any help.

sending a message to network computer

$
0
0

Hello everyone I'm trying to create a script that will send a message to a network computer LAN . I 'm trying to find a way to be able to write many message in the same powershell session example a reply without opening this powershell script again, here is my script.

$message = read-host -prompt "type your message here"
$computername = Read-Host -Prompt "type a computername"
$session = "*"
msg $session /server:$computername $message

Best

 

Help with Functions!!!

$
0
0

I am learning about functions. For some reason the scripts work as individual pieces but when placed in a function and run nothing happens. Any help would be greatly appreciated. Here is what I have so far:

 

#Clears the screen

cls

 

#Generates a prompt that asks the user to input which computer to access

$computer= Read-Host "Enter the computer name:"

 

#Create a function that list the software installed on the computer specified by input argument

function getSoftwareInfo ($softwareInfo) {

 

#Gets the Programs installed on the computer

$softwareInfo = gwmi Win32_Product -computername $computer | Sort-Object Vendor, Name | Format-Table Vendor, Name

}

 

#Create a function that lists the free disk space and percentage of disk space used on the computer

function diskCheck {

 

#Gets the freespace of the C: Drive

$freeSpace = gwmi -class win32_logicaldisk -computername $computer  | where {$_.deviceid -eq"C:"} | select-object {$_.freespace / 1GB}

#Gets the total space of the C: Drive

$totalSpace = gwmi -class win32_logicaldisk -computername $computer | where {$_.deviceid -eq "C:"} | select-object {$_.size / 1GB}

 

#Gets percentage of disk space used

 

$percentUsed = (($totalSpace - $freeSpace)/$totalSpace) * 100

}

 

#calls the functions

getSoftwareInfo

diskCheck

 

#Create readable texts for both functions

$installed = "The programs that are installed in the " + $computer + " are as follows: " + $softwareInfo

$diskfree = "Free space available on C: drive:" + $freeSpace +" GB"

$diskused = "Percent of disk space used on C:" + $percentUsed +"%"

 

#Exports softwareInfo to CSV file

Export-Csv -path C:\Scripts\Computer_Software.csv -inputObject $installed

 

#Exports diskCheck to CSV file

Export-Csv -path C:\Scripts\Computer_hdspace.csv -inputObject $diskfree, $diskused

 

#Writes output to the screen

Write-Host $installed

Write-Host $diskfree

Write-Host $diskused

 

 

 

Powershell pass switch to scriptmethod

$
0
0

Is there a correct syntax for passing a switch to a scriptmethod like you can to a function

you can pass a switch to a function:

function func ($parm1,$parm2='defaultvalue',[switch]$switch1) {write-host $switch1}

func -switch1

True

How do you pass a switch to a scriptmethod ?

$obj = New-Object Object

Add-Member -in $obj ScriptMethod 'method' { param($parm1,$parm2,[switch]$switch1) write-host $switch1 }

$obj.method(-switch1) # doesn't work

The advantage of the way functions handle things is that you don't have to specify every positional parm or switch if they are not needed for the particular call or their default value is adequate (like how cmdlets work). If you add a parm3 later, you don't have to revisit every call and add that parm unless it is needed.

As far as I can tell, with scriptmethods, you'd need to set values for and specify every parm and switch positionally. If you add a parm3 later, you'd have to go to every function call and adjust it.

You might ask, 'then why don't you just use functions'. I would like to use the object model where you keep the data attached to the object (I use note properties) and then the methods to manipulate that data.

 

checking command line arguments passed to PS script are present...

$
0
0

Hi,

I am very new to using Power Shell and I am stumped...

I need to pass 4 arguments to my PS script and I am not sure of the most efficient way of checking that they have all be specified on the command line...

 

$devicename=$args[0]

$ipaddress=$args[1]

$username=$args[2]

$password=$args[3]

 

I need the script to exit if one or more value is missing, preferably with a message saying that there is a problem... If all values are present the script should continue to process...

I am sure this is very simple - but I just don't know how to go about sorting it...

Any help will be most appreciated...

Thanks in advance

 

Martin

Viewing all 10624 articles
Browse latest View live