Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

How do I convert C# code to PowerShell script?

$
0
0

Completely new to powershell scripting here. But how do i convert this block of c# code to a powershell script? Is there a tool out there that newbies like myself can use? 

public void BuildReport(string objectId, bool includesWebs, bool includesLists, bool includesLibraries, bool includesItems)
{
	private bool m_includeWebs = includeWebs;
	private bool m_includeLists = includeLists;
	private bool m_includeLibrariess = includeLibrariess;
	private bool m_includeItems = includeItems;
	try
	{
		using (new SPMonitoredScope(this.GetType().FullName + CommonResources.Colon + new StackFrame(0).GetMethod().Name))
		{
			using (SPSite site = new SPSite(m_siteUrl))
			{
				if (ExpandADGroups || ShowGroupDescriptions)
				{
					InitADGroups(site);
				}
				initializeReport(site);
				m_serverUrl = GetServerUrl(site);
				InitReportColumns(site);
				AppendReportInfo(site, objectId);
				AppendHeaderRow();
				switch (m_scope)
				{
					case ReportScope.Site:
						BuildSiteReport(site);
						break;
					case ReportScope.Subsite:
						BuildSiteReport(site);
						break;
					case ReportScope.Library:
						BuildSiteReport(site, objectId);
						break;
					case ReportScope.List:
						BuildSiteReport(site, objectId);
						break;
				}
			}
		}
	}
	catch (Exception ex)
	{
	}
}


I really appreciate the help...



How can I use export-csv from invoke-command to get correct data format

$
0
0

Hi expert:

              Below is my code,when I use output to screen,the output format  like this

Username          Ipaddress             Port              Server Name                 Time                            
--------                 --------                 --------          ----------------                   --------
yyccmm                                                                       yy-mm                  2014/3/21                    

            

  But when I export to csv(invoke-command -computername xx,yy,zz -scriptblock $command -ArgumentList $name | export-csv),  the data format  chnage to

"PSComputerName","RunspaceId","PSShowComputerName","ClassId2e4f51ef21dd47e99d3c952918aff9cd","pageHeaderEntry","pageFooterEntry","autosizeInfo","shapeInfo","groupingEntry"
"yy-mm","72a287e5-3c96-47d2-9d98-5444c9b5f792","True","033ecb2bc07a4d43b5ef94ed5a35d280",,,,"Microsoft.PowerShell.Commands.Internal.Format.TableHeaderInfo",
"yy-mm","72a287e5-3c96-47d2-9d98-5444c9b5f792","True","9e210fe47d09416682b841769c78b8a3",,,,,

           

  How can I export data format like output to screen fromat~  thanks~

$command={param($name)
  $xmlfilter=[xml]@"<QueryList><Query Id="0" Path="Security"><Select Path="Security">
                 *[EventData[Data[@Name='targetUserName'] and (Data='$name')   ] ]
                  and
                 *[System[(EventID='4624')]]</Select></Query></QueryList>"@
$napevents=get-winevent -filterxml $xmlfilter
$napevents  | ft  `
@{Name="Username";expression={$_.properties[5].value}},`
@{Name="Ipaddress";expression={$_.properties[18].value}},
@{Name="Port";expression={$_.properties[19].value}},
@{Name="Server Name";expression={$_.Machinename}} ,
@{Name="Time";Expression={$_.TimeCreated.ToString('g')}} | write-output""
}
invoke-command -computername xx,yy,zz -scriptblock $command -ArgumentList $name




Script/Batch to Rename Files (with s)

$
0
0
I have a collection of files in a directory with this filename formats:

<ZIPNAME><DATE>.ZIP.<Source>.<Destination>.<TIMECREATED>

Where:

ZipName - Flexible; filename is created automatically
Source / Destination - Normal value is from 0001 to 9999

Sample:

Account20080909.zip.1.0001.0901
Account20080909.zip.1.0025.0902
Account20080909.zip.1.0110.0910
Group20080909.zip.1.0110.0905
Group20080909.zip.1.0025.0903
Group20080909.zip.1.0001.0904

Scenario:

I want to copy the file and rename file with 0001 by removing the trailing extensions, just retain the zip file, see sample output:

Account20080909.zip.1.0001.0901 to Account20080909.zip
Group20080909.zip.1.0001.0904 to Group20080909.zip


Is this possible?

Script to Get CPU and Memory Information of Multiple Computers Listed in Text File

$
0
0
Script to Get CPU and Memory Information of Multiple Computers Listed in Text File.

Pranay (MCSE, MCITP)

script to rename files

$
0
0

i have this list of files:


001_14 - rua da murça nº 42
004_14 - rua da picareta nº 2
011_14 - rua da viela nº 40
....etc

i need to rename to this form:

001_14
004_14
011_14
....etc

can anyone help me doing this?..

thanks


Powershell Script Help

$
0
0

I got this script from one of the PowerShell Jump MVA lessons.

It works great, but I need to be able to get all the drive free spaces if there are more than one. How can it be modified to get those if there are a variable number of drives in each machine.

Function Get-CompInfo{
    [CmdletBinding()]
    Param(
        #Want to support multiple computers
        [Parameter(Mandatory=$True,
                    ValueFromPipeline=$true,
                    ValueFromPipelineByPropertyName=$true)]
        [String[]]$ComputerName,
        #Switch to turn on Error logging
        [Switch]$ErrorLog,
        [String]$LogFile = 'c:\errorlog.txt'
    )
    Begin{}
    Process{
        foreach($Computer in $ComputerName){
            $os=Get-Wmiobject -ComputerName $Computer -Class Win32_OperatingSystem
            $Disk=Get-WmiObject -ComputerName $Computer -class Win32_LogicalDisk -filter "DeviceID='c:'"
            $Prop=[ordered]@{ #With or without [ordered]
                'ComputerName'=$computer;
                'OS Name'=$os.caption;
                'OS Build'=$os.buildnumber;
                'FreeSpace'=$Disk.freespace / 1gb -as [int]
            }
        $Obj=New-Object -TypeName PSObject -Property $Prop 
        Write-Output $Obj

        } 
    }
    End{}
}

Post reboot required login automatical & log off

$
0
0

Hi Techies,

I’m new to powershell scripting world,

I need a script for post reboot automatically log particular user account in to the server and launch application & logoff automatically.

Thanks for your help on this.


Regards,

SreeM


Overwriting Powershell Output to Excel

$
0
0
I am wondering how to control the output from powershell to Excel or CSV.  I have a script that runs through hundreds of computers and when it outputs to excel and CSV it continuously overwrites the first row instead of going to a new row for each machine.  I have looked through the script and I can't find any command such as the "nonewrow" command.  What commands do I need to add to the script in order to make it advance to the next row?

Powershell Map user to computername

$
0
0

Hi all

Im looking to modify my below line to include acolumn in the csv file toinclude the users computername

Get-ADUser -filter * -SearchBase "ou=users,dc=contoso,dc=com" | select samaccountname,givenname,surname | Export-CSV <filename>

I have looked about but cant find anything that works.  Here I scan the OU for user info but need the computername mapped to the user.

I dont want to use a logon script but gather this info from my machine like softperfect netscanner does, it uses wmi.

Anyone have an inkling?

Thanks

Confiseis


confuseis


If statement to run a portion of an existing script over again....

$
0
0

Forgive me if this is such a noobish question...but I am pretty much a beginner at PS scripting.  I have the following script that  requests credentials and establishes a connection to my Exchange server then requests user input for a "job number" and creates a public folder with email enabled and also creates a set of transport rules for the folder.  It works wonderfully

Function Establish-EXCConnection
{

$Usercredential = Get-Credential

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://mail.server.com/Powershell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Session
}

Function Add-JobFolder
{

$jobshort = $jobnumber -replace "[^0-9]",''

new-PublicFolder -name "$jobshort" -path "\email job file"
enable-mailpublicfolder "\email job file\$jobshort"
set-mailpublicfolder "\email job file\$jobshort" -HiddenFromAddressListsEnable $true
New-TransportRule -Name "$jobshort" -SubjectContains "$jobshort","$jobnumber" -copyto "$jobshort@lobar.com"

}

Establish-EXCConnection
$jobnumber = read-host -Prompt "Enter Job Number with XX-XXX Format"
Add-JobFolder $jobnumber

My issue is when I have multiple job numbers or folders that I need to create.  I would have to exit the power shell session and re-establish a connection for each job number I have to create. 

How do I create an if statement (I think that is what I need) that will prompt the user after finishing if they have more job numbers to enter with a Yes or No....then run the script again?

Thanks in advance for any help anyone can give!


cpu performance script

$
0
0

Hello!

I am completly new to PowerShell. I just started to learn it last week by taking MS virtual academy course, so i got a picture of what can be done with it but i don´t yet have the skills to get it done my self :( I don´t have any earlier experience with programming or making scripts either so this task is well abow my skills!

My problem is that i have a server that i want to measure performance on and send me an alert when an treshold is reach. I want it to send me and email when the cpu is over 90% for lets say 5 min. To get Windows to send notification when a cpu peaks over 90% is no problem but this is not very intresting, the intresting thing is when the load on the server stays over 90% for an period of time.

So i figure that i need a script that measures the cpu time once every minute, and if the cpu time is over 90% five times in a row it will trigger function in the script that send an alert via email. 

I would appreciate all the help i can get in this matter!  

Best regards /Henrik

Start-Service failing

$
0
0

Hi,

I'm running the following script from a powershell running as administrator:

Start-Service MyCoolService

I get the following error:

================================

Start-Service : Service 'My Cool Service (MyCoolService)' cannot be started due to the following error

: Cannot start service MyCoolService on computer '.'.

At line:1 char:14

+ Start-Service <<<<  MyCoolService

    + CategoryInfo          : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service],

   ServiceCommandException

    + FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceCommand

================================

I don't know what the fully qualified error means and can't find anything that helps me out.  Any ideas?

Thanks,

-Mike

Powershell script to gather failed logon attempts by event id and type from the security events log

$
0
0

I need to export the information from the Failed logins within the Domain Controller Security events log. I need to then export it into an excel spreadsheet. Anyone know where to start and should I be doing this via vbscript or Windows Powershell.

Trying to run program off network location using GPO with Power shell script.

$
0
0

Hello All,

Not much of a script writer. I am giving it a shot.  My issue is that I need to run a application update across our network and I am trying to do it with as little hands on as possible. So I was planning to push a GPO with a power shell script in it to run the program with elevated privileges. 

Little background:

We are running on a domain and end users do not have admin rights.

The application is stored on a share on our network that is open to all domain users.

The installer user name and password is a temp one and will only be valid for the 30 min window when everyone logs in at the beginning of the day.

So this is what I have so far.

$username = "USER"

$password = "PASSWORD"


$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))



Start-Process PSQLv11Patch_Client_x86.msp -Credential ($credentials) -WorkingDirectory \\Server\Folder\Folder1\Folder2\filder3\PSQLv11sp3_x32\


But for some reason I keep getting :

Start-Process : This command cannot be run due to the error: The system cannot find the file specified.
At line:10 char:1
+ Start-Process PSQLv11Patch_Client_x86.msp -Credential ($credentials) -WorkingDir ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand

Any help you could give would be great.

Thanks,

jdfmonkey


Warning when using exchange snap-in in PowerShell

$
0
0

When I run PowerShell scripts for creating and modifying users to Enable-Mailbox or Disable-Mailbox, the first time the script is run I get a warning shown below.  I believe that error does not always happen the next time.  Here is the relevant parts of the code I believe:

Function Load-PSSnapin { 
# ----------------------------------------------------------------------------------------------
# Function to load Exchange Snap-In(s) into PowerShell
#  - Checks to see if the snap-in is already loaded
#  - Checks to see if the snap-in is available to be imported
#  - Adds snap-in to PowerShell
# ----------------------------------------------------------------------------------------------
    Param( [parameter(Mandatory=$true)][string]$Name ) 
    if( -Not( Get-PSSnapin -Name $Name -ErrorAction:SilentlyContinue ) ) { 
        if( Get-PSSnapin -Registered | Where-Object { $_.Name -eq $Name } ) { 
            # Snap-in is available, but not loaded; Add the snap-in
            Add-PSSnapin -Name $Name 
        } else { 
            # Module not available on the computer
            Write-Host -ForegroundColor Red "ERROR: The specified snap-in '$name' is not found on this computer."
            break
        } # End if
    } else { 
        # Module is already loaded
    } # End if
} # End Function Load-Module <...other stuff...>


        # Get the user's current information
        $user = Get-ADUser $Change -Properties * -Server $Server

        # Remove email from account
        if( $user.mail.Length -gt 0 ) {
            # Load the Microsoft Exchange Admin Snap-In
            Load-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010 
            Disable-Mailbox -Identity $user.SamAccountName -DomainController $Server -Confirm:$false
        }

I get the following output but it DOES enable or disable the user but gives this big'ol'warning:

WARNING: The cmdlet extension agent with the index 0 has thrown an exception in OnComplete(). The exception is:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at Microsoft.Exchange.Data.Storage.ExchangePrincipal.get_ServerFullyQualifiedDomainName()
   at Microsoft.Exchange.Data.Storage.MailboxSession.Initialize(MapiStore linkedStore, LogonType logonType,
ExchangePrincipal owner, DelegateLogonUser delegateUser, Object identity, OpenMailboxSessionFlags flags,
GenericIdentity auxiliaryIdentity)
   at Microsoft.Exchange.Data.Storage.MailboxSession.<>c__DisplayClass12.<CreateMailboxSession>b__10(MailboxSession
mailboxSession)
   at Microsoft.Exchange.Data.Storage.MailboxSession.InternalCreateMailboxSession(LogonType logonType,
ExchangePrincipal owner, CultureInfo cultureInfo, String clientInfoString, IAccountingObject budget, Action`1
initializeMailboxSession, InitializeMailboxSessionFailure initializeMailboxSessionFailure)
   at Microsoft.Exchange.Data.Storage.MailboxSession.CreateMailboxSession(LogonType logonType, ExchangePrincipal owner,
 DelegateLogonUser delegateUser, Object identity, OpenMailboxSessionFlags flags, CultureInfo cultureInfo, String
clientInfoString, PropertyDefinition[] mailboxProperties, IList`1 foldersToInit, GenericIdentity auxiliaryIdentity,
IAccountingObject budget)
   at Microsoft.Exchange.Data.Storage.MailboxSession.ConfigurableOpen(ExchangePrincipal mailbox, MailboxAccessInfo
accessInfo, CultureInfo cultureInfo, String clientInfoString, LogonType logonType, PropertyDefinition[]
mailboxProperties, InitializationFlags initFlags, IList`1 foldersToInit, IAccountingObject budget)
   at Microsoft.Exchange.Data.Storage.MailboxSession.OpenAsSystemService(ExchangePrincipal mailboxOwner, CultureInfo
cultureInfo, String clientInfoString)
   at Microsoft.Exchange.ProvisioningAgent.MailboxLoggerFactory.XsoMailer.Log(AdminLogMessageData data,
LogMessageDelegate logMessage)
   at Microsoft.Exchange.ProvisioningAgent.AdminLogProvisioningHandler.OnComplete(Boolean succeeded, Exception e)
   at Microsoft.Exchange.Provisioning.ProvisioningLayer.OnComplete(Task task, Boolean succeeded, Exception exception)
PS D:\PowerShell\Development>

I do NOT get this if I use the EMS directly and not just load the snappin with my script.  Is there a different way to load it to make it function properly?


Find this post helpful? Does this post answer your question? Be sure to mark it appropriately to help others find answers to their searches.


How to uninstall PowerShell 1.0

$
0
0
Hi,  Please point me to instructions for uninstalling PowerShell 1.0 from XP Pro so that I can install version 2.  I have read that service packs can remove the 1.0 uninstaller.  Is the XP Pro uninstaller for PowerShell 1.0 available for download?

The support article http://support.microsoft.com/kb/926139/ does not include instructions for removing 1.0 for my XP Pro system.

In Currently installed programs, Windows PowerShell(TM) 1.0 does not appear on my XP Pro system and consequently I am unable to click Remove .

How to uninstall Windows PowerShell in Windows XP

<script type="text/javascript"> loadTOCNode(3, 'moreinformation'); </script> In Windows XP, follow these steps to uninstall Windows PowerShell 1.0:
  1. Click Start , click Run , type appwiz.cpl , and then click OK .
  2. Click to select the Show updates check box.
  3. In the Currently installed programs list, click Windows PowerShell(TM) 1.0 , and then click Remove .
  4. Follow the instructions to remove the following entry:
    Windows PowerShell(TM) 1.0

Script a report for AD Attribute 'Smart Card Is Required For Interactive Logon'

$
0
0

I'm in need to create a script that would dump a report on all the users in my domain that do NOT have the AD attribute 'Smart card is required for interactive logon'. I know a script is the best way to do this but I'm not sure how to tackle this. I'm hoping that someone would be able to help me out

Thanks!

How to specify named parameter for Word.Application Close() method

$
0
0

When I'm using the Word.Application to open a document I want to specify parameters for file converstion. However, when I only want to specify the READONLY, FORMAT parameters I have to specify every single parameter until I get to the 10th one.

Is there any way to pass NAMED parameters like the VBA code samples show on MSDN?

$pdf = "c:\temp\test.pdf"
$objWord = New-Object -Com Word.Application
$objWord.Visible = $true $objDocument = $objWord.Documents.Open($Pdf,$True,$True,$False,"","",$True,"","",22) 

For example, I would love if it worked like this:

$objDocument = $objWord.Documents.Open(@{filename=$pdf;ReadyOnly=$True;FileFormat=22})

http://msdn.microsoft.com/en-us/library/office/ff836084(v=office.15).aspx


Levi Stevens | Technical Consultant Dell Services

Microsoft Script Control

$
0
0

I am importing a json file to Excel using Microsoft Scripting Controls.

I am trying to set up several sheets within the workbook, where only one piece of data is the variant between sheets. However I can't get the Script Engine to reset from sheet to sheet. What do I need to do to have the script engine reset each time? Thanks

Public Sub InitScriptEngine()
    Set ScriptEngine = New ScriptControl
    With ScriptEngine
        .Language = "JScript"
        .AddCode "function getProperty(jsonObj, propertyName) { return jsonObj[propertyName]; } "
        .AddCode "function getSubProperty(jsonObj, podId, propertyName) { return jsonObj.gallery.podCache[podId][propertyName]; } "
        .AddCode "function getKeys(jsonObj) { var keys = new Array(); for (var i in jsonObj.gallery.podCache) { keys.push(i); } return keys; } "
    End With
End Sub

Assembly load-from context error? (PS 2, .NET 3.5)

$
0
0

Hi,

I have what I think is a load context problem in Powershell 2, .NET 3.5. I want to automate Attachmate Reflection which has 7 namespaces in 4 DLLs:

Add-Type -Path "C:\Program Files\Attachmate\Reflection\Attachmate.Reflection.dll" Add-Type -Path "C:\Program Files\Attachmate\Reflection\Attachmate.Reflection.Framework.dll" Add-Type -Path "C:\Program Files\Attachmate\Reflection\Attachmate.Reflection.Emulation.IbmHosts.dll" Add-Type -Path "C:\Program Files\Attachmate\Reflection\Attachmate.Reflection.Emulation.OpenSystems.dll"

[appdomain]::CurrentDomain.GetAssemblies()

$reflectionApplication = [Attachmate.Reflection.Framework.MyReflection]::CreateApplication() #constructor
$reflectionApplication | Get-Member

I can see the assemblies and the members of $reflectionApplication:

GAC Version Location --- ------- -------- False v2.0.50727 C:\Program Files\Attachmate\Reflection\Attachmate.Reflection.dll False v2.0.50727 C:\Program Files\Attachmate\Reflection\Attachmate.Reflection.Framework.dll False v2.0.50727 C:\Program Files\Attachmate\Reflection\Attachmate.Reflection.Emulation.IbmHosts.dll False v2.0.50727 C:\Program Files\Attachmate\Reflection\Attachmate.Reflection.Emulation.OpenSystems.dll TypeName: Attachmate.Reflection.Framework.Application Name MemberType Definition ---- ---------- ---------- ApplicationClosed Event System.EventHandler ApplicationClosed(System.Object, System.EventArgs) ApplicationClosing Event Attachmate.Reflection.Framework.ApplicationClosingEventHandler ApplicationClosing(System.Object, Attachmate.Reflection.Framework.... ApplicationClosedEventSink Method System.Void ApplicationClosedEventSink(System.Object sender, System.EventArgs eventArgs) ApplicationClosingEventSink Method System.Void ApplicationClosingEventSink(System.Object sender, Attachmate.Reflection.Framework.ApplicationClosingEventArgs eventArgs) Close Method System.Void Close(Attachmate.Reflection.Framework.ApplicationCloseOption closeOption) ControlDisposedEventSink Method System.Void ControlDisposedEventSink(System.Object control) CreateControl Method System.Object CreateControl(string sessionFilePath), System.Object CreateControl(System.Guid controlType) CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) Dispose Method System.Void Dispose() Equals Method bool Equals(System.Object obj) GetControlByInstanceId Method System.Object GetControlByInstanceId(System.Guid controlInstanceId) GetControlsByFilePath Method System.Object[] GetControlsByFilePath(string filePath) GetControlsByName Method System.Object[] GetControlsByName(string name) GetHashCode Method int GetHashCode() GetLifetimeService Method System.Object GetLifetimeService() GetObject Method System.Object GetObject(string objectMoniker) GetType Method type GetType() InitializeLifetimeService Method System.Object InitializeLifetimeService() ReleaseResource Method System.Void ReleaseResource() ToString Method string ToString() Wait Method System.Void Wait(int waitTime) ControlCount Property System.Int32 ControlCount {get;} RemoteObject Property System.Object RemoteObject {get;}

 I can run $reflectionApplication."ControlCount" and it returns an integer. But when I try the overloaded method CreateControl() I get this cast error:

[Attachmate.Reflection.Emulation.IbmHosts.IIbmTerminal] $terminal = $reflectionApplication.CreateControl([string] "C:\Program Files\Attachmate\Reflection\HKCU_Reflection_2011\setup.rd3x") Exception calling "CreateControl" with "1" argument(s): "Unable to cast transparent proxy to type 'Attachmate.Reflection.Framework.IBase'." At C:\Users\jsa004\Documents\Personal\scripts\attachmate2.ps1:50 char:105+ [Attachmate.Reflection.Emulation.IbmHosts.IIbmTerminal] $terminal = $reflectionApplication.CreateControl <<<< ($controlType)+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : DotNetMethodException


I would prefer not to have to mess around with the GAC to resolve this.

Any help is much appreciated!



Viewing all 15028 articles
Browse latest View live


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