Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Powershell parsing question

$
0
0

Hi all,

I'm trying to parse the below data and write it into a CSV file. I need to gather all the bolded data and the script that I have allows me to get the first 16 items (which is  exactly what i need) however i'm missing one vital piece of information and that is the enclosure name (hilighted in bold and underlined). I'm not sure how i can add it. Any help would be appreciated and thanks in advanced. 

--Gaz  


HP BladeSystem Onboard Administrator
(C) Copyright 2006-2012 Hewlett-Packard Development Company, L.P.

INFWPSC04A [SCRIPT MODE]> show server names


Bay Server Name                   Serial Number   Status   Power   UID Partner
--- ----------------------------- --------------- -------- ------- --- -------
  1 304XUSE02                USEECB      OK       On      Off
  2 305XUSE02                USEECJ      OK       On      Off
  3 306XUSE02                USEECL      OK       On      Off
  4 308XWRL11                USEECD      OK       On      Off
  5 304XUSE03                USEECP      OK       On      Off
  6 305XUSE03                USEECH      OK       On      Off
  7 306XUSE03                USEECN      OK       On      Off
  8 308XWRL12                USEECA      OK       On      Off
  9 304XUSE04                USEECK      OK       On      Off
 10 305XUSE04                USEECM      OK       On      Off
 11 306XUSE04                USEECF      OK       On      Off
 12 100XHLD07                USEECR      OK       On      Off
 13 304XUSE05                USEECE      OK       On      Off
 14 305XUSE05                USEECS      OK       On      Off
 15 306XUSE05                USEEC9      OK       On      Off
 16 100XHLD08                USEECC      OK       On      Off
Totals: 16 server blades installed, 16 powered on.

INFWPSC04A [SCRIPT MODE]>

show server names


HP BladeSystem Onboard Administrator
(C) Copyright 2006-2011 Hewlett-Packard Development Company, L.P.

INFWPSC02A [SCRIPT MODE]> show topology


Rack Topology (top-down)


Rack UUID: ALL5
Rack Name:11


         Enclosure Name           Status  Local   IP Address         UUID
-------------------------------- -------- ----- --------------- --------------
INFWPSC02                     OK       Yes   10.1.1.1         E121ALL5 

INFWPSC02A [SCRIPT MODE]>
show topology

PowerShell Script

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

$vara = get-childitem -name "D:\ServerInfo\"

$varb = foreach ($q in $vara) {gc "D:\ServerInfo\$q"}

#loop through the text and assign the result to commaSeparatedInfo
$commaSeparatedInfo = foreach($line in $varb){
    #if the line starts with a number or any number of spaces followed by a number, process it, otherwise we'll ignore it
    if($line -match "^\s*\d"){
        #remove the leading spaces if there are any
        $line = $line -replace "^\s*"
        #replace any remaining spaces between the text with a comma and emit the line (should have csv at this point)
        $line -replace "\s+",","
    }
}
#create the header to parse the csv as an array
$header = "Bay","ServerName","SerialNumber","Status","Power","UID","Partner"
#convert the csv into objects with convertfrom-csv using the header
$parsedInfo = $commaSeparatedInfo|convertfrom-csv -Header $header
#select out just the fields that you want.
$EncData = $parsedInfo|select Bay,ServerName,SerialNumber


PowerShell Web Access - Creating "Self-Serve" Behaviour

$
0
0

Hi all,

I am exploring PowerShell Web Access and I'm looking to set it up to offer self-serve capabilities to Dev/QA.  Basically I want to Dev/QA to only be able to execute scripts (no running cmdlets, etc) and only in particular directories.

The goal of this is to allow Dev/QA to get access to the scripts I would normally run, but be able to run them when I'm away for whatever reason (while still keeping them out of the rest of the system).

Can anyone point me in the right direction?

Thanks.

New-ImapSubscription

$
0
0

I'm trying to run a PS script to setup users connected accounts on Exchange , i'm connected to PS with ContosoAdmin:

 

New-ImapSubscription -Name "My IMAP" -Mailbox mailbox@domain.com -EmailAddressuser1@contoso.com -IncomingUserName "contoso\user1" -IncomingPassword (ConvertTo-SecureString -String 'Pa$$word' -AsPlainText -Force) -IncomingServer imap.contoso.com  -IncomingSecurity None -IncomingPort 143

 

ContosoAdmin has 'Recipient Management' and 'Organization Management' roles assigned

 

the error I get is cant find user or group (it is the valid user mailbox). If I remove the '-Mailbox' it creates the Connected Account in ContosoAdmin account.

 

I need to run this for 40 user as a batch

 

It would appear that ConosoAdmin doesn't have permission to create the Connected Account in User1

Tx

Mark


devlinfisher*

Remotely executing an invoke-sqlcmd fails

$
0
0

When remotely executing an invoke-sqlcmd fails.  A simple query such as:

Invoke-Command -ComputerName ComputerName -ScriptBlock{
$qry = "SELECT SERVERPROPERTY('ServerName') AS ServerName,
   SERVERPROPERTY('ProductVersion') AS ProductVersion,
   SERVERPROPERTY('ProductLevel') AS ProductLevel,
   SERVERPROPERTY('Edition') AS Edition, 
   SERVERPROPERTY('EngineEdition') AS EngineEdition;" 
   Invoke-Sqlcmd -Query $qry} -ConfigurationName SQLSession

I get the following error:

[ComputerName] Connecting to remote server failed with the following error message : The WS-Management service cannot process the request. The resource URI (http://sche
mas.microsoft.com/powershell/SQLSession) was not found in the WS-Management catalog. The catalog contains the metadata that describes resources, or logical endpoints. For 
more information, see the about_Remote_Troubleshooting Help topic.+ CategoryInfo          : OpenError: (:) [], PSRemotingTransportException+ FullyQualifiedErrorId : PSSessionStateBroken

I have run Enable-WSManCredSSP Server on the SQL server and  tried to run Enable-WSManCredSSP -Role Client -DelegatedCredentials * on a Windows 7 x32 workstation but I get the following error:

Enable-WSManCredSSP : A parameter cannot be found that matches parameter name 'DelegatedCredentials'.
At line:1 char:55+ Enable-WSManCredSSP -Role Client -DelegatedCredentials <<<<  *+ CategoryInfo          : InvalidArgument: (:) [Enable-WSManCredSSP], ParameterBindingException+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.WSMan.Management.EnableWSManCredSSPCommand
I have tried the Enable-WSManCredSSP with the actual server name instead of a wildcard and it still fails.

Use PS to install SCCM2012 Client on a remote machine

$
0
0

Does anyone successfully use PS to install SCCM2012 Client on remote windows 7 machine? it seems not working by using ([WMICLASS]"\\$ip\ROOT\CIMV2:win32_process").Create("cmd.exe /C MD C:\APPS\SCCM2012_Client\ccmsetup.exe")

but other apps ok like MS Visio, Project and so on.

Find only one different extension, whole path, last write time, only files and over 260

$
0
0

Hello!

I need some help with my PowerShell script. This is what I got so far.

Get-ChildItem p:\ -Include *.* -Recurse | Where { ! $_.PSIsContainer } | Select-Object Extension,LastWriteTime | Sort-Object -Property Extension -Unique | Out-File c:\skriptit\file.txt

I need to find out every different extension what there is our shared files. I want only one file for each extension and it have to be last time when somebody used(write) it. I also need whole path and over 260 character
long. Also every subfolders and only files, no folders.

This script what I have, it take first extension it finds and take that Last Write Time. Also threre is no full path and no over 260 characters.

Mika

Etract data to Excel

$
0
0

Good day im a newbie

i have a text file (LOG.TXT )that contain the following info below.


S e r i a l N u m b e r      M X L 1 0 3 0 8 3 4          TW-BW-JU-IT-12

S e r i a l N u m b e r      M X L 1 0 3 0 9 2 5           TW-BW-JU-IT-13

S e r i a l N u m b e r      M X L 1 0 3 0 9 5 9          TW-BW-JU-IT-14

i want to export this info to a Excel file using Powershell  , Maintainting the same row and column structure .

 i WAS TRYIN TO USE THE SCRIPT BELOW . BUT IT ISNT OUTPUTING CORRECTLY.

$path = "C:\Users\\Desktop\logStroe\LOG.txt"
$outPath = $path -replace ".txt",".xls"
Get-Content -path $path |
ForEach-Object {$_ -replace " ","," } |  
Out-File -filepath $outPath

Script to create a folder that can print a certain amount of files - works for Libre but not for Word.

$
0
0

I've got this script 

[int]$copies = Read-Host "Number of copies"
 for ($i=0;$i -lt $copies;$i++) {
     Get-ChildItem "C:\Users\USER NAME\Desktop\PrintMe" | foreach {Start-Process -FilePath $_.FullName -Verb Print}
 }

Which works fine if the documents are in libre format, but if they are in word MS Word starts opening up an instance for every document and then comes up with loads of pop up messages about the Template file and thing's. 

This come's up although there is a printer linked to the computer and I'm able to print thing's out by opening the file and selecting print....

Not too sure what's it's struggling with


Assistance with my script to find all opened windows (applications running) on remote computer

$
0
0

Hello,

I have the following script whereby I want to list all the running (opened) applications on a remote computer.  It's a shared computer between two people who use the same generic ID.  Before one RDP's into it, I thought it would be interesting to see if any apps are opened before logging in. 

Here is the code:

$cred = Get-Credential
Invoke-Command -ComputerName server123 {Get-Process *mail* | Where {$_.MainWindowHandle} | Select Name,MainWindowTitle} -Cred $cred

It works in that it asks for my credentials and runs without any error...but this script also does not display any running applications. I'm not sure what it should show. Perhaps I need to add a line of code to display what it found?

Another bit of info I would like to use in this script is to also confirm that the generic ID is logged in at the time I run this script.  I could use the following bit of code:

get-wmiobject Win32_ComputerSystem -computername server123 | format-table -property username

But when I run this code I get an access denied message. I'm assuming I need to use the Get-Credential again from my first script, but I'm unsure how to use it in the get-wmiobject?

Any help you can provide would be greatly appreciated.

Thank you.


Details of a thread in Powershell

$
0
0

How can I get the CPU consumption of all threads running in a process thru powershell, in a format similar to this

I can't find any processor information when I run gwmi win32_thread|select -First 1. And theStart Address is numeric !?!  Am I missing something  :(;


Ayan Mullick Principal Infrastructure Engineer. British Petroleum.

[DOC BUG] in Start-Job cmdlet parameter -FilePath

$
0
0

In http://technet.microsoft.com/en-us/library/hh849698.aspx, it can be read:

<#

-FilePath<String>

... Enter the path and file name of the script or pipe a script path toStart-Job...

... 

Accept Pipeline Input? false

#>

The 2 informations are contradictory.

First, the documentation says it's possible to pipe data to Start-Job cmdlet's -FilePath parameter.

Later, it says this parameter doesn't accept pipeline input.


... don't disturb ... life is short, and I have to think what I'll do next ...

Usage of Set-DNSServerSetting

$
0
0

Hello all togehter,

I have severall Windows 2012 DCs with DNS installed. Until now, I use a batch file to configure the DNS for my demands. Since 2012, I can configure DNS with PowerShell and I want to fully migrate the cmd commands to PowerShell. Basically this should work, but I do not fully understand how the Set-DNSServerSetting cmdlet works.

For example, I want to change the setting for "LocalNetPriority" and "RoundRobin".

If I use Get-DNServerSetting -All, PowerShell displays me the current values for these settings (true or false). And as the cmdlet help shows in the example, I can use "Get-DNSServerSetting -All -Computername Server007 | Set-DNSServerSetting" to copy the settings from an existing server.

However, I don't want to copy the settings, but just write the settings as I defined, like "$MySettings | Set-DNSServerSetting", where $MySettings contains the Object with all settings I need. But how can I create such an object in my script, without copying the settings from another DNS server?

To be more clear: I wish the Set-DNSServerSetting cmdlet would work like "Set-DNSServerSetting -RoundRobin $true -LocalNetPriority $true", but it doesn't. Who has a workaround for me?

Thanks,
Michael

PS: I know, dnscmd would also work in my PowerShell script, but I try to use PowerShell cmdlets.

Combine Multiple Output into Single Output using powershell command

$
0
0

Is there a way merge all the below output into single output using powershell script. The output needs to be in html format sorting out the user in mailbox size on descending order


$User = Get-MailboxServer MBX01 | Get-Mailbox -ResultSize 10  
$EASOutput =  $MBXV01  | ForEach-Object { Get-MobileDeviceStatistics -Mailbox $_.Identity} | Select-Object identity,devicemodel,LastSuccessSync}

$CASOutput =  Get-Casmailbox User1 | ft Name, ActivesyncEnabled, MAPIEnabled
$MBXOutput =  Get-Mailbox User1 | ft servername, alias, primarysmtpaddress, database
$MBXStat = Get-MailboxStatistics -Identity User1 | ft displayname, TotalItemSize, TotalDeletedItemSize, Itemcount

Exchange Queries


Powershell unzip with shell.application not working when launched from windows service

$
0
0

I have a deployment agent on a machine implemented as a windows service. Service is 32-bit and runs on windows server 2008R2 x64 SP1 with powershell V2. Powershell script requires elevation and to run under x64 because of dependency to powershell module 'IIS Administration'. To achieve this, the service starts a cmd file which in turn launches powershell x64 console:

C:\WINDOWS\sysnative\WindowsPowerShell\v1.0\powershell.exe "Start-Process C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell -ArgumentList '-ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File C:\Temp\EndJobCmd\Install.ps1' -Verb RunAs"

This seems to work well. The problem I have is that the script has a sequence where it unpacks a zip file to a destination folder using shell.application, this works fine when triggered manually on the server or through the task scheduler, but when triggered from the service it does not extract any files at all (cannot see any errors thrown by the script but it seems to continue to execute as it logs a successful message to the event log after finishing).

Unzip sequence looks like:

    $shell = New-Object -com shell.application
    $pkg = $shell.namespace($sourceFile)
    $installDir = $shell.namespace($targetDir)
    $installDir.Copyhere($pkg.items(), 20)
Any advice greatly appreciated. I have searched some and seen a few people with similar issue but have yet to find a solution.

Cannot connect to Office 365 using Powershell on Windows 7 SP1

$
0
0
Hi,

I was trying to connect to Office 365 using windows azure active directory module for Windows Powershell.

$Cred = Get-Credential
Connect-MsolService -Credential $cred

It failed on my windows 7 machine with the error

Connect-MsolService : Unable to authenticate your credentials. Make sure that your user name is 
in the format: <username>@<domain>. If this issue persists, contact support.

This issue happened in Windows 7 SP1 OS.

But, when I tried the same thing on a Windows 2008 R2 VM, it connected successfully.

This means that the account I was trying to login does have the permissions.

Both the machines ( windows 7 and windows server 2008 R2) have the following pre-requisites installed:

Install Microsoft Online Services Sign-in Assistant: http://www.microsoft.com/en-us/download/details.aspx?id=39267

Windows Azure Active Directory Module for Windows PowerShell (64-bit version) 

I checked for other settings needed for this to work at :

(Though these settings are for Windows 8, I have all these settings in Windows 7 as well)

http://community.spiceworks.com/how_to/show/45453-how-to-prepare-a-windows-8-64-bit-pc-to-manage-windows-azure-ad-office-365-using-windows-powershell 

Can someone please tell what is going wrong on my Windows 7 SP1 environment.


Thanks,
Gagan


Gagan


Remove exchange forwarding for some users and loop help

$
0
0
Hi

We need to remove the email forwarding settings for some of our users. Some users have their email forwarded to "My email [BLAH]" where "[BLAH]" always appears in the name of the contact that the main mailbox forwards to. 

The email address of the "[BLAH]" contact also includes "blah.com" in the external email field.

We need to remove the forwarding for any user who's forwarding settings points to a contact with "[BLAH]" in the name or blah.com in the contacts external email field.

Anyone know some Powershell that might help? I can do the disabling but I can't do the look to go through and check the exsting settings and only remove if ...

Any help much appreciated.

Olly

Change file asociations via Powershell

$
0
0

hi guys, someone know how can we change a file asociation using powershell?

I want to make the same that we can achieve using Explorer and the option "Choose Default Program"

[BUG] in Start-Job cmdlet when piping job's name to the cmdlet: the resulting job can't be found by Receive-Job cmdlet.

$
0
0

Consider this script:

$job=[pscustomobject]@{Name='Qwerty'} | sajb -ScriptBlock {ps}

The job is created, successfully, with the name specified above.

It can be seen commanding:

gjb

Nonetheless, trying to receive the result from it (the job) results in job not found error.

rcjb -job $job


... don't disturb ... life is short, and I have to think what I'll do next ...

Set default printer $CheckBox with powershell

$
0
0

Hey I was hoping someone could help me out with this. I am building a GUI to add a printer and giving it a check box to set it to the default.  Everything is working correctly except that when it set it to the default it locks up the PowerShell ISE.  I have tried to change several thing to get it to work but I'm not having any luck.   Any help would be greatly appreciated.

Here is my script:

#Load Required visaual basic libraries for Input Windows
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | Out-Null


#Static Variables
#---------------------------------------------------------------
#This is the path to the print server
$printserv= "................"
$x = 0 
$computername = Get-Content env:computername

#Object Properties
#---------------------------------------------------------------
#~~< Form1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Form1 = New-Object System.Windows.Forms.Form
$Form1.ClientSize = New-Object System.Drawing.Size(199, 178)
$Form1.Text = "Form1"
#~~< Label1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Label1 = New-Object System.Windows.Forms.Label
$Label1.Location = New-Object System.Drawing.Point(13, 13)
$Label1.Size = New-Object System.Drawing.Size(172, 23)
$Label1.TabIndex = 5
$Label1.Text = "What is the name of your printer?"
#~~< TextBox1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$TextBox1 = New-Object System.Windows.Forms.TextBox
$TextBox1.Location = New-Object System.Drawing.Point(12, 43)
$TextBox1.Size = New-Object System.Drawing.Size(173, 20)
$TextBox1.TabIndex = 3
$TextBox1.Text = ""
$TextBox1.CharacterCasing = 'Upper'
#~~< Button2 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Button2 = New-Object System.Windows.Forms.Button
$Button2.Location = New-Object System.Drawing.Point(110, 69)
$Button2.Size = New-Object System.Drawing.Size(75, 23)
$Button2.TabIndex = 2
$Button2.Text = "Cancel"
$Button2.UseVisualStyleBackColor = $true
#~~< Button1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Button1 = New-Object System.Windows.Forms.Button
$Button1.Location = New-Object System.Drawing.Point(12, 69)
$Button1.Size = New-Object System.Drawing.Size(75, 23)
$Button1.TabIndex = 1
$Button1.Text = "Add Printer"
$Button1.UseVisualStyleBackColor = $true
#~~< CheckBox1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$CheckBox1 = New-Object System.Windows.Forms.CheckBox
$CheckBox1.Location = New-Object System.Drawing.Point(12, 108)
$CheckBox1.Size = New-Object System.Drawing.Size(173, 24)
$CheckBox1.TabIndex = 0
$CheckBox1.Text = "Make the printer defualt?"
$CheckBox1.UseVisualStyleBackColor = $true
#~~< Defualt Printer >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Def = New-Object -ComObject WScript.network

$Form1.Controls.Add($Label1)
$Form1.Controls.Add($TextBox1)
$Form1.Controls.Add($Button2)
$Form1.Controls.Add($Button1)
$Form1.Controls.Add($CheckBox1)



#Button Functions
$Button1.Add_Click({
    if ($TextBox1.TextLength -gt 0){
        $printpath=$printserv+$TextBox1.text
        printui.exe /in /n $printpath
        Write-Host "Add a printer"
        }    
    If ($CheckBox1.Checked){
        #printui.exe /y /n $printpath | Out-Null
        $def.SetDefaultPrinter($printpath)
        Write-Host "Check Box If"
        }
    })

$Button2.Add_Click({$Form1.Close()})

$TextBox1.Select()

$Form1.ShowDialog()

regex

$
0
0

Welcome

I need from html file or $http1_request.responseText extract string beetweem two others strings

Got this html code

 

http://pastebin.com/B4zW03zp

 

$wynik = $http1_request.responseText
$wynik | out-file wynik.html

 

 

Now i wanna assign

$communication = string beetween<tr class="dialogLineItem"><td align=center width=50%% valign=top>Communications Version</td><td align=center valign=top>&nbsp; and&nbsp;</b></td></tr><tr class="dialogLineItem"><td align=center width=50%% valign=top>Contact

$contact = string beetween <tr class="dialogLineItem"><td align=center width=50%% valign=top>Contact</td><td align=center valign=top>&nbsp;and&nbsp;</b></td></tr><tr class="dialogLineItem"><td align=center width=50%% valign=top>Contact Email

 

This wont to work

$html = Get-Content .\html.htm  | out-string
[regex]::match($html,'(?<=\<
first string\>).+(?=\<last string
\>)',"singleline").value.trim()
 


Viewing all 21975 articles
Browse latest View live