Quantcast
Channel: Windows PowerShell Forum
Viewing all 2562 articles
Browse latest View live

Formating Powershell Output in Rich Text Box

$
0
0

Hi All,

I am using Primal Forms to create a GUI for a script that will display the AD Information about the user account.

The code below works but the output is difficult to read, is there any way i can format it to make is more readable?

#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0
# Generated On: 18/10/2012 16:27
# Generated By: adminnp
########################################################################

#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
#endregion

#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$richTextBox1 = New-Object System.Windows.Forms.RichTextBox
$textBox1 = New-Object System.Windows.Forms.TextBox
$button1 = New-Object System.Windows.Forms.Button
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects

#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$processData= 
{
#TODO: Place custom script here
$richTextBox1.Text = $richTextBox1.Text.Clear

$user=($textBox1.TEXT)

Get-ADUser -Filter {SamAccountName -eq $user} -Properties * -OutVariable data
	foreach ($line in $data) {
		$richTextBox1.Appendtext(($line | Select * | Out-String ))
	}

}

$handler_form1_Load= 
{
#TODO: Place custom script here

}

$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
	$form1.WindowState = $InitialFormWindowState
}

#----------------------------------------------
#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 536
$System_Drawing_Size.Width = 748
$form1.ClientSize = $System_Drawing_Size
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 347
$System_Drawing_Point.Y = 182
$form1.Location = $System_Drawing_Point
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 574
$System_Drawing_Size.Width = 764
$form1.MaximumSize = $System_Drawing_Size
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 574
$System_Drawing_Size.Width = 764
$form1.MinimumSize = $System_Drawing_Size
$form1.Name = "form1"
$form1.Text = "User Info Tool"
$form1.add_Load($handler_form1_Load)

$richTextBox1.Anchor = 15
$richTextBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 8
$System_Drawing_Point.Y = 56
$richTextBox1.Location = $System_Drawing_Point
$richTextBox1.Name = "richTextBox1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 468
$System_Drawing_Size.Width = 728
$richTextBox1.Size = $System_Drawing_Size
$richTextBox1.TabIndex = 2
$richTextBox1.Text = ""
$richTextBox1.font = "Arial"

$form1.Controls.Add($richTextBox1)

$textBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 160
$System_Drawing_Point.Y = 12
$textBox1.Location = $System_Drawing_Point
$textBox1.Name = "textBox1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 249
$textBox1.Size = $System_Drawing_Size
$textBox1.TabIndex = 1

$form1.Controls.Add($textBox1)

$button1.Anchor = 9

$button1.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 463
$System_Drawing_Point.Y = 12
$button1.Location = $System_Drawing_Point
$button1.Name = "button1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 126
$button1.Size = $System_Drawing_Size
$button1.TabIndex = 0
$button1.Text = "Go"
$button1.UseVisualStyleBackColor = $True
$button1.add_Click($processData)

$form1.Controls.Add($button1)

#endregion Generated Form Code

#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null

} #End Function

#Call the Function
GenerateForm


Move-Item integrity

$
0
0

Does the cmdlet Move-Item perform any sort of checksum internally to ensure there is no corruption during the file being moved?

Thanks!

Active Directory: New-ADUser character escaping

$
0
0

Hi,

I am using the Active Directory Cmdlets in Windows PowerShell.
When I try to create a user NewAdUser -Name "Hello\, world" -.... the following error occurs:

New-ADUser : The name provided is not a properly formed account name
At C:\BatchScript\UserAdd\AdminUserAdd.ps1:49 char:11
+ New-ADUser <<<<  -Instance $userInstance -Name "Hello\, world" -Description "Administrative User" Path $path
    + CategoryInfo          : NotSpecified: (CN=Hello\\\, wo...,DC=env-e,DC=int:String) [New-ADUser], ADException


Is there a way to create a comma-seperated username (fullname) with the New-ADUser cmdlet since the same thing works with ADSI.

Thank you very much for your assistence!

 

Search for audit failure on AD specific user

$
0
0

Hi I need some help with a script or just command that does this for me.

Searches the Security Event Log for failure audits on a specific account and outputs the events. 

Say i want to do a search for user "somethingxx" in the security log and only get the event ID's that match with the username and failure audit. Cant figure out how to do this. 

                                                                

Office 365 cmdlets: Issues with Get-MsolGroupMember

$
0
0

I had previously asked a question on the Office 365 forums, but the support team there suggested I ask my question here instead. First, I noticed that the -SearchString parameter was not working as expected with Get-MsolGroupMember.

I'm trying to write a script in which I check to see if a certain user is a member of a security group. I've used other Office 365 cmdlets where using -SearchString is as simple as putting the string to search for. What am I missing here?

Get-MsolGroupMember -GroupObjectId [Object ID for group I want to check] -SearchString $str

Get-MsolGroupMember : Invalid value for parameter.  Parameter name: SearchString.

At line:1 char:20

+ Get-MsolGroupMember <<<<  -GroupObjectId [xxxxxxx] -SearchString $str

    + CategoryInfo          : OperationStopped: (:) [Get-MsolGroupMember], MicrosoftOnlineException

    + FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.PropertyValidationException,Microsoft.Online.Admini 

   stration.Automation.GetGroupMember

The suggested workaround was to get all the members of the group and use a Where clause to find the particular group member I was looking for. However, that doesn't answer the initial question, plus I ran into the limitation that Get-MsolGroupMember was returning a maximum of 500 results, even with the -All switch. The group I am trying to search has over 4,000 members, so using that method I would only get accurate results if the user I was looking for happened to be in the top 500 results.

At this point, I've found an entirely different solution for the script I was writing, but I'd still like some answers about the behaviors of this cmdlet. Thanks!

Poweshell for cluster failover help

$
0
0

So, I worked out a command that will allow me to remotely failover a 2008 R2 cluster and it works great for the first failover, but on subsiquent failovers it fails over and then fails right back before the command completes, see below:

PS C:\> Get-ClusterGroup -cluster c-test-ps-ab

Name                                    OwnerNode                                                                 State
----                                    ---------                                                                 -----
TEST-VPS-2008-A                         test-ps-2008-b                                                           Online
Cluster Group                           test-ps-2008-b                                                           Online
Available Storage                       test-ps-2008-b                                                           Online


PS C:\> Get-ClusterNode -cluster test-vps-2008-a | Get-ClusterGroup | Move-ClusterGroup

Name                                    OwnerNode                                                                 State
----                                    ---------                                                                 -----
TEST-VPS-2008-A                         test-ps-2008-a                                                           Online
Cluster Group                           test-ps-2008-a                                                           Online
Available Storage                       test-ps-2008-a                                                           Online


PS C:\> Get-ClusterNode -cluster test-vps-2008-a | Get-ClusterGroup | Move-ClusterGroup

Name                                    OwnerNode                                                                 State
----                                    ---------                                                                 -----
TEST-VPS-2008-A                         test-ps-2008-b                                                           Online
Cluster Group                           test-ps-2008-b                                                           Online
Available Storage                       test-ps-2008-b                                                           Online
TEST-VPS-2008-A                         test-ps-2008-a                                                           Online
Cluster Group                           test-ps-2008-a                                                           Online
Available Storage                       test-ps-2008-a                                                           Online

Any idea why this would be happening or how to prevent it in the future?

how to pull the latest diff backup from a single folder that contains Multiple diff backups for multiple databases.

$
0
0

Hi,

I have a dilemma...

I have been tasked with automating the restore process for one of our DR sites.

One of the specific things I will be doing is restore all full backups from a  network share then

I need to restore the latest differential for each of the databases I am restoring.

I'm not having any problems getting the correct full back ups restored as I have written another script that purges old full backups...

However, the differencials are a different matter entirely.

I was trying this little bit of code to pull back the latest differencials and then I was simply going to do a -contains to make sure the correct diff was restored to the correct db...

$fil

$filesdif = Get-ChildItem $Directory -filter "*dif*.sqb" -rec | Where-Object {($_.Directory -notlike $Directory+"\master\FULL" )}
$filesSorted = $filesdif | group name | foreach {@($_.group | sort {[datetime]$_.lastwritetime} -desc)[0]} | sort {$_.name}

 

However, this doesn't seem to be working at the filenames contain date/time stamps in them... for example I might have 5 diffs

for acme database and they would like something like follows....

 

DIFF_(local)_acme_20121228_152352.sqb
DIFF_(local)_acme_20121229_152352.sqb
DIFF_(local)_acme_20130102_152352.sqb

etc...

well since they all have different names.. I can't really sort on the name as is...

I was wondering if anyone else has run into something similar. I was wondering if there would be a way to modify the
"group name" section to actually strip off the date time part just for the comparison...

I tried something like...

$filesSorteddif = $filesdif | group $_.fullname.replace("\d{8}\_\d{6}\.\w{3}$","")  | foreach {@($_.group | sort {[datetime]$_.lastwritetime} -desc)[0]} | sort {$_.name}   

But no luck...

Any help would be greatly appreciated.

Thanks!

Jason


esSorted=$files|groupname|foreach{@($_.group|sort{[datetime]$_.lastwritetime}-desc)[0]}|sort{$_.name}



Copy Directory structure with ACL permission script

$
0
0
Hi All,

Can anyone here please help me with the Powershell script which can perform the NTFS directory structure copy along with the ACL and its permission (just the directory only without the files) ?

Thanks

/* Server Support Specialist */


Monitoring Logshipping

$
0
0


Could you please suggest me SCRIPT for only failed RESTORING jobs(jobname is like %LSrestore%).so that it helps me to monitor Logshipping status in secondary server.

I need to setup email alert when the restoring job fails in secondary server.we have more than 300 DBs in logshipping.

 

Please suggest me

Powershell script stops at first line

$
0
0

Hello,

I am new to powershell. I have some items I need to replace in files, and a powershell script seems like the best way for me to do it. Here is an example of what I am generating in excel:

Etc

I have these commands saved in a Ps1 file. However, when I run it, only the first command goes through for file 1 and none of the other files are changed. Any help would be appreciated!

(Get-Content file1.txt) | ForEach-Object { $_ -replace "choice a", "choice b" } | Set-Content file1.txt
(Get-Content file2.txt) | ForEach-Object { $_ -replace "choice a", "choice c" } | Set-Content file2.txt

Any way to load a PSSnapin quicker?

$
0
0

Im wondering if there is a way to load a subset of a PSSnapin?  Take for instance the Microsoft Lync PSSnapin, which takes nearly 60 seconds to load on the server where I want to execute the powershell script.  Basically im only using get-csuser and enable-csuser, So I was wondering is there a way to only load those two cmdlets and any other cmdlets that those need to function properly.

I doubt this is a possibility, but I thought i'd ask anyway.

Thanks,

James

Windows Form, have button return to disabled if text box is empty?

$
0
0

New to forms here :).... I'm trying to have my validate button return to disabled (grayed out) when the text box goes from having text to no text. I can get this work initially when the text box is empty. Below is my code as well as a screen shot of the form. I've come this far with method 'add_TextChanged'. Top Pic: no text in text box so validate button is disabled (grayed out). Middle Pic: text box has text so validate button is enabled. Bottom Pic: text in text box has been deleted, but validate button remains enabled. 

$Form = New-Object system.Windows.Forms.Form
$Form.Text = "Validate Name"
$Form.Width = 420
$Form.Height = 130
$Form.StartPosition = "CenterScreen"

$LabelFolder = New-Object System.Windows.Forms.Label
$LabelFolder.Location = New-Object System.Drawing.Size(10,10) 
$LabelFolder.Size = New-Object System.Drawing.Size(90,15) 
$LabelFolder.Text = "Folder Name:"
$LabelFolder.BackColor = $Color
$Form.Controls.Add($LabelFolder)

$ButtonFolderVal = New-Object System.Windows.Forms.Button
$ButtonFolderVal.Enabled = $false
$ButtonFolderVal.Location = New-Object System.Drawing.Size(320,10)
$ButtonFolderVal.Size = New-Object System.Drawing.Size(60,22)
$ButtonFolderVal.Text = "Validate"
$ButtonFolderVal.Add_Click({Validate})
$Form.Controls.Add($ButtonFolderVal)

Function Validate
{
	$Form.Controls.Remove($LabelValRes)
	$LabelValRes = New-Object System.Windows.Forms.Label
	$LabelValRes.Location = New-Object System.Drawing.Size(10,40) 
	$LabelValRes.Size = New-Object System.Drawing.Size(200,15) 
	
	if ($TextBoxFolder.Text -eq "Something Valid")
	{
		$LabelValRes.Text = "$($TextBoxFolder.Text) is valid"
	}
	else
	{
		$LabelValRes.Text = "$($TextBoxFolder.Text) is not valid"
	}

	$Form.Controls.Add($LabelValRes)
}

$TextBoxFolder = New-Object System.Windows.Forms.TextBox 
$TextBoxFolder.Location = New-Object System.Drawing.Size(110,10) 
$TextBoxFolder.Size = New-Object System.Drawing.Size(200,15)
$TextBoxFolder.add_TextChanged({$ButtonFolderVal.Enabled = $true})
$Form.Controls.Add($TextBoxFolder)

$Form.ShowDialog()

                   

Thanks for the help, Joey



Run PowerShell script from C# writing to input pipe

$
0
0

Hello,

I am trying to run a PowerShell script from C# (I have no control over what's in the script). The script may have a prompt like "Press enter to continue". So my goal is:

1. Get text output from the script (easy, many examples available)

3. If output contains "Press enter to continue", write a blank line to the running script's pipe to make it finish its job and quit

4. If output does contain that prompt, just let it exit by itself without sending any input

Note that commands in this PS script also try to get at script's file path, so I can't read script from file and pass it as text. It has to be executed as a script so it knows where it's located.

I have done this with .exes and batch files before. All you do in that case is process.StandardInput.WriteLine() which "types" enter into the input stream of script you are trying to control. But this does not work with Power Shell. How do I do this?

I have tried using PS object model like so:

using (Pipeline pipeline = runspace.CreatePipeline()) { Command command = new Command(scriptPS, true, true);   pipeline.Commands.Add(command);   pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);   pipeline.Input.Write("\n");   Collection<PSObject> psresults = pipeline.Invoke();

   //...

But I get an error because the script prompts:

"A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows."

I also tried using Process, and running PowerShell with -File switch to execute the script, then write to StandardInput with C#. I get no errors then, but the input is ignored and doesn't make it to PowerShell.

Please help!


List remote shares without WMI

$
0
0

Hi,

We have a NAS (NetApp) that has shared some folders (not hidden ones). I looking for a way to enumerate these shares so I can use these shares to locate resources that are places on these shares. Since this is not a Windows server I can't use WMI to query the list of shares.

Anyone have an idea or example on how I can list the shares of a remote CIFS box that isn't capable of WMI?

How on earth do you uninstall PS3? I do not want to have PS 2 and 3 running on the same machine I REALLY want to get PS 3 OFF! How? :)

$
0
0

Hi,

I'm on Windows Server 2008 R2.

The PS 3 uninstall is not in features - the ISE is listed but it is greyed out - no way can I select to uninstall or reinstall...

Remove a KB? Nope it's not there...

I need to use Powershell 2 not 3...

I do not need or want PS 3 on this server - how on earth do you get it off and leave PS 2 only so that it is the default PS version to run...?

Thanks.


mapping and removing a network drive after pulling out the informaton

$
0
0

I am writing a script for searching a string in a file on two different computers and in two different files.

Both the computers are part of xyz domain and requires alternate credentails.

My question is how to

Map network drives of both the computers using different credentails

Run the below function

Remove the network drives.

Function as{
$server=Get-Content f:\sl.txt

foreach ($s in $server){
$file = Get-Content "file location " | Select-String "alc" -ErrorAction Silentlycontinue


if ($file -ne $null)
{
 "$s $file"
}
else
{
 "$s Does not contains the string"
}
}}

find files on sftp site using winscp and process if exist

$
0
0

 I have a script(not PS) that calls Winscp using a PrivateKey and userid that connects to Sftp and does a DIR against a folder on
that site. Does anyone have a PS script that would do that same function but check for the existence of 2 files then if both
are found create a local file like 2files-exist.txt that I could use to trigger a process? If only 1 of the 2 files exists just
report back that finding via email or something. I need a process like this because until both files arrive I don't want to launch
the load process.

 Thanks.

 

How to get particular data from a text file

$
0
0

Hi All,

I have been trying to make a script that will get the host IP and read IP's from a text file, and then pass them to a varible so I can then automatically map them to the nearest Printer based on IP:

This is what I have so far:

$ip = (Get-WmiObject -class win32_NetworkAdapterConfiguration -Filter 'ipenabled = "true"').ipaddress[0] | %{"{0:000}.{1:000}.{2:000}.{3:000}" -f
@([int[]]$_.split('.'))}

$ip1 = $ip.Substring(4,7)
Write-Host $ip1

$Check = Get-Content "C:\PRINTERINV.csv" | Where-Object {$_ -like $IP1 }

Write-Host $Check

#$String=[string]::join("`n", (Get-Content "C:\PRINTERINV.csv"))
#$Check = $String.contains($ip1) #$PrinterPath = $Path + $String

#$net = new-Object -com WScript.Network 
#$net.AddWindowsPrinterConnection($PrinterPath)



#Write-Host $String
#Write-Host $PrinterPath

However, for some reason the $Check variable is null,  any ideas?

Kind Regards,

Sean,

download file from web on remote pc

$
0
0

The Following script works perfectly on a local computer but issue occurs when it runs on a remote computer.

$machines = Get-Content "c:\Users\metho\Desktop\test.txt"
[ScriptBlock] $script = { 

$url = "http://192.168.1.1/stuff/test.txt"
$target = "C:\Documents and Settings\metho\Desktop\test.txt"

[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$vbnt = New-Object Microsoft.VisualBasic.Devices.Network
$vbnt.DownloadFile($url, $target,"","",$true, 40, $true)

}
$cred = Get-Credential
$sessions = $machines | New-PSSession -Credential $cred
Invoke-Command -ScriptBlock $script -Session $sessions
$sessions | Remove-PSSession

i get the following the error message if i run on a remote pc!

Exception calling "DownloadFile" with "7" argument(s): "The operation has timed out"+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : DotNetMethodException

i dont know what i am doing wrong, can anyone help?


Reading Security event log

$
0
0

Hi gang.

I want to read the securitylog of all domain controller - and at first it seems like an easy task....

However - i ran into some issue about speed.

i found 3 ways of reading the log:

1) get-eventlog
2) get-winevent
3) $Evelog = new-object system.diagnostics.eventlog("Security", $servername)

Option 1 seems to be an old fasion way of doing it

Option 2: get-winevent -logname security -ComputerName $Servername is working, esp when using -filterhashtable, however it seems very slow ($events = Get-WinEvent -FilterHashTable @{LogName="Security"; StartTime=$sdate; EndTime=$edate} -computername $servername

Option 3: is also working, however once i have the eventlog object, i have dificulties reading the log:
  $evelog.entries[100] change content from time to time.. and as such when looping thou all the entries (or a range) im not sure i will actually read all the entries (if the log have new entries and old entries have been deleted)

So what is the best way forward here - i need a relativly fast way of retrieving 5-10 specific event id.


/Stig

Viewing all 2562 articles
Browse latest View live


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