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

RegEx Help - Start with "string" but not include it

$
0
0

Hi Sirs,

I am writing a code and I had some problems with the RegEx part.

8=FIX.4.2| 9=253| 35=8| 128=XYZ| 34=124| 49=CCG| 56=ABC_DEFG04| 
52=20100208-18:51:42| 55=RRC| 37=NF 0015/02082010| 11=NF 0015/02082010| 17=0| 
20=0| 39=0| 150=0| 54=2| 38=1000| 40=2| 44=55.3600| 59=0| 31=0| 32=0| 14=0| 
6=0| 151=1000| 60=20100208-18:51:42| 58=New order| 30=N| 1=ABC123ZYX| 207=N| 
47=A| 10=037| 

From the message above (FIX 'tag'='value') I need to extract the value and the '=' sign.

For example:

User typed: 60

System returns: =20100208-18:51:42

I am using the following RegEx statement:

\|60=[\s\S]*?[^\|]*

So it returns: 

| 60=20100208-18:51:42

How can I remove the '| tag' part ? :/

Thank you in advance.


Move-item: The process cannot access the file because it is being used by another process.

$
0
0

Hey,

I have a powershell script where I first use Get-childitem to receive a number of files.
Then I do some stuff with it and try to move the file afterwards.

Unfortunately if I am using a lot of files I receive very often the error:
The process cannot access the file because it is being used by another process.

Even -Force parameter does not help further.
Based on my look around it is not used by another process.
I think it is still 'in use' by powershell from script commands previously.

Is there any way to 'see' if the file is still in use currently and wait for this to end?
Or can I 'close' the current usage of the file?

Thank you :)

How do I pin RUN.LNK when there are no Pin To Taskbar verbs

$
0
0

None of the RUN.LNK shortcuts have a Pin To Taskbar verb.
I have searched every RUN.LNK on the disk, none have it.

Under Win8, I can find the Run icon in the Apps panel, and pin it to both the Taskbar and Start Menu.
This is a puzzler for me.

I want to do this with Powershell, which I already use to pin all the other common apps that I require.

[Forum FAQ] Using PowerShell to assign permissions on Active Directory objects

$
0
0

As we all know, theActiveDirectoryAccessRule class is used to represent an access control entry (ACE) in the discretionary access control list (DACL) of an Active Directory Domain Services object.

To set the permissions on Active Directory objects, the relevant classes and their enumerations are listed as below:

System.DirectoryServices.ActiveDirectoryAccessRule class:

http://msdn.microsoft.com/en-us/library/system.directoryservices.activedirectoryaccessrule(v=vs.110).aspx

System.DirectoryServices.ActiveDirectoryRightsclass:

http://msdn.microsoft.com/en-us/library/system.directoryservices.activedirectoryrights(v=vs.110).aspx

System.Security.AccessControl.AccessControlType class:

http://msdn.microsoft.com/en-us/library/w4ds5h86(v=vs.110).aspx

System.DirectoryServices.ActiveDirectorySecurityInheritance class:

http://msdn.microsoft.com/en-us/library/system.directoryservices.activedirectorysecurityinheritance(v=vs.110).aspx

In this article, we introduce three ways to get and set the ACE on an Active Directory object. In general,we use Active Directory Service Interfaces (ADSI) orActive Directory module cmdletswith the Get-Acl and Set-Acl cmdlets to assign simple permissions on Active Directory objects. In addition, we can use the extended rights and GUID settings to execute more complex permission settings.

Method 1: Using ADSI

  1. Get current permissions of an organization unit (OU)

We can use the PowerShell script below to get current permissions of an organization unit and you just need to define the name of the OU.

$Name = "OU=xxx,DC=com"

$ADObject = [ADSI]"LDAP://$Name"

$aclObject = $ADObject.psbase.ObjectSecurity

$aclList = $aclObject.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier])

$output=@()

       

foreach($acl in $aclList)

     {

       $objSID = New-Object System.Security.Principal.SecurityIdentifier($acl.IdentityReference)

           

       $info = @{

         'ActiveDirectoryRights' = $acl.ActiveDirectoryRights;

         'InheritanceType' = $acl.InheritanceType;

         'ObjectType' = $acl.ObjectType;

         'InheritedObjectType' = $acl.InheritedObjectType;

         'ObjectFlags' = $acl.ObjectFlags;

         'AccessControlType' = $acl.AccessControlType;

         'IdentityReference' = $acl.IdentityReference;

         'NTAccount' = $objSID.Translate( [System.Security.Principal.NTAccount] );

         'IsInherited' = $acl.IsInherited;

         'InheritanceFlags' = $acl.InheritanceFlags;

         'PropagationFlags' = $acl.PropagationFlags;

       }

           

       $obj = New-Object -TypeName PSObject -Property $info

       $output+=$obj}

$output

In the figure below, you can see the results of running the script above:

Figure 1

  2. Assign a computer object with Full Control permission on an OU

We can use the script below to delegate Full Control permission to the computer objects within an OU:

$SysManObj = [ADSI]("LDAP://OU=test….,DC=com") #get the OU object

$computer = get-adcomputer "COMPUTERNAME" #get the computer object which will be assigned with Full Control permission within an OU

$sid = [System.Security.Principal.SecurityIdentifier] $computer.SID

$identity = [System.Security.Principal.IdentityReference] $SID

$adRights = [System.DirectoryServices.ActiveDirectoryRights] "GenericAll"

$type = [System.Security.AccessControl.AccessControlType] "Allow"

$inheritanceType = [System.DirectoryServices.ActiveDirectorySecurityInheritance] "All"

$ACE = New-Object System.DirectoryServices.ActiveDirectoryAccessRule $identity,$adRights,$type,$inheritanceType #set permission

$SysManObj.psbase.ObjectSecurity.AddAccessRule($ACE)

$SysManObj.psbase.commitchanges()

After running the script above, you can check the computer object in Active Directory Users and Computers (ADUC) and it is under the Security tab in OU Properties.

Method 2: Using Active Directory module with the Get-Acl and Set-Acl cmdlets

You can use the script below to get and assign Full Control permission to a computer object on an OU:

$acl = get-acl "ad:OU=xxx,DC=com"

$acl.access #to get access right of the OU

$computer = get-adcomputer "COMPUTERNAME"

$sid = [System.Security.Principal.SecurityIdentifier] $computer.SID

# Create a new access control entry to allow access to the OU

$identity = [System.Security.Principal.IdentityReference] $SID

$adRights = [System.DirectoryServices.ActiveDirectoryRights] "GenericAll"

$type = [System.Security.AccessControl.AccessControlType] "Allow"

$inheritanceType = [System.DirectoryServices.ActiveDirectorySecurityInheritance] "All"

$ACE = New-Object System.DirectoryServices.ActiveDirectoryAccessRule $identity,$adRights,$type,$inheritanceType

# Add the ACE to the ACL, then set the ACL to save the changes

$acl.AddAccessRule($ace)

Set-acl -aclobject $acl "ad:OU=xxx,DC=com"

Method 3: Using GUID setting

The scripts above can only help us to complete simple tasks, however, we may want to execute more complex permission settings. In this scenario, we can use GUID settings to achieve that.

The specific ACEs allow an administrator to delegate Active Directory specific rights (i.e. extended rights) or read/write access to a property set (i.e. a named collection of attributes) by setting ObjectType field in an object specific ACE to the rightsGuid of the extended right or property set. The delegation can also be created to target child objects of a specific class by setting theInheritedObjectType field to the schemaIDGuid of the class.

We choose to use this pattern: ActiveDirectoryAccessRule(IdentityReference, ActiveDirectoryRights, AccessControlType, Guid, ActiveDirectorySecurityInheritance, Guid)

You can use the script below toassign the group object with the permission to change user password on all user objects within an OU.

$acl = get-acl "ad:OU=xxx,DC=com"

$group = Get-ADgroup xxx

$sid = new-object System.Security.Principal.SecurityIdentifier $group.SID

# The following object specific ACE is to grant Group permission to change user password on all user objects under OU

$objectguid = new-object Guid 00299570-246d-11d0-a768-00aa006e0529 # is the rightsGuid for the extended right User-Force-Change-Password (“Reset Password”) class

$inheritedobjectguid = new-object Guid bf967aba-0de6-11d0-a285-00aa003049e2 # is the schemaIDGuid for the user

$identity = [System.Security.Principal.IdentityReference] $SID

$adRights = [System.DirectoryServices.ActiveDirectoryRights] "ExtendedRight"

$type = [System.Security.AccessControl.AccessControlType]"Allow"

$inheritanceType = [System.DirectoryServices.ActiveDirectorySecurityInheritance] "Descendents"

$ace = new-object System.DirectoryServices.ActiveDirectoryAccessRule $identity,$adRights,$type,$objectGuid,$inheritanceType,$inheritedobjectguid

$acl.AddAccessRule($ace)

Set-acl -aclobject $acl "ad:OU=xxx,DC=com"

The figure below shows the result of running the script above:

Figure 2

In addition, if you want to assign other permissions, you can change the GUID values in the script above. The common GUID values are listed as below:

$guidChangePassword     = new-object Guid ab721a53-1e2f-11d0-9819-00aa0040529b

$guidLockoutTime        = new-object Guid 28630ebf-41d5-11d1-a9c1-0000f80367c1

$guidPwdLastSet         = new-object Guid bf967a0a-0de6-11d0-a285-00aa003049e2

$guidComputerObject     = new-object Guid bf967a86-0de6-11d0-a285-00aa003049e2

$guidUserObject         = new-object Guid bf967aba-0de6-11d0-a285-00aa003049e2

$guidLinkGroupPolicy    = new-object Guid f30e3bbe-9ff0-11d1-b603-0000f80367c1

$guidGroupPolicyOptions = new-object Guid f30e3bbf-9ff0-11d1-b603-0000f80367c1

$guidResetPassword      = new-object Guid 00299570-246d-11d0-a768-00aa006e0529

$guidGroupObject        = new-object Guid BF967A9C-0DE6-11D0-A285-00AA003049E2                                          

$guidContactObject      = new-object Guid 5CB41ED0-0E4C-11D0-A286-00AA003049E2

$guidOUObject           = new-object Guid BF967AA5-0DE6-11D0-A285-00AA003049E2

$guidPrinterObject      = new-object Guid BF967AA8-0DE6-11D0-A285-00AA003049E2

$guidWriteMembers       = new-object Guid bf9679c0-0de6-11d0-a285-00aa003049e2

$guidNull               = new-object Guid 00000000-0000-0000-0000-000000000000

$guidPublicInformation  = new-object Guid e48d0154-bcf8-11d1-8702-00c04fb96050

$guidGeneralInformation = new-object Guid 59ba2f42-79a2-11d0-9020-00c04fc2d3cf

$guidPersonalInformation = new-object Guid 77B5B886-944A-11d1-AEBD-0000F80367C1

$guidGroupMembership    = new-object Guid bc0ac240-79a9-11d0-9020-00c04fc2d4cf

More information:

Add Object Specific ACEs using Active Directory Powershell

http://blogs.msdn.com/b/adpowershell/archive/2009/10/13/add-object-specific-aces-using-active-directory-powershell.aspx


Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.



How to Connect to One Server, Extract Data, Connect to Second Server, and Insert that Extracted Data into Table on Second Server

$
0
0
I have the following code that connect to my Central Management Server and loops through each server extracting data and inserting into a table on a different server.  I only want to connect to one server, extract data, connect to a second server, and insert that data into a table on that second server.

I am new to PowerShell and I have been trying to tweek the code below to do this.  However, I have been unsuccessful.  Can anyone help me learn how to do this or point me to a web page demonstrating this?




<#
.SYNOPSIS
Creates a DataTable for an object
.DESCRIPTION
Creates a DataTable based on an objects properties.
.INPUTS
Object
    Any object can be piped to Out-DataTable
.OUTPUTS
   System.Data.DataTable
.EXAMPLE
$dt = Get-Alias | Out-DataTable
This example creates a DataTable from the properties of Get-Alias and assigns output to $dt variable
.NOTES
Adapted from script by Marc van Orsouw see link
Version History
v1.0   - Chad Miller - Initial Release
v1.1   - Chad Miller - Fixed Issue with Properties
.LINK
http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx
#>
function Out-DataTable
{
    [CmdletBinding()]
    param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject)

    Begin
    {
        $dt = new-object Data.datatable  
        $First = $true 
    }
    Process
    {
        foreach ($object in $InputObject)
        {
            $DR = $DT.NewRow()  
            foreach($property in $object.PsObject.get_properties())
            {  
                if ($first)
                {  
                    $Col =  new-object Data.DataColumn  
                    $Col.ColumnName = $property.Name.ToString()  
                    $DT.Columns.Add($Col)
                }  
                if ($property.IsArray)
                { $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 }  
                else { $DR.Item($property.Name) = $property.value }  
            }  
            $DT.Rows.Add($DR)  
            $First = $false
        }
    } 
     
    End
    {
        Write-Output @(,($dt))
    }

} #Out-DataTable




Import-Module “sqlps” -DisableNameChecking



  

foreach ($RegisteredSQLs in dir -recurse SQLSERVER:\SQLRegistration\'Central Management Server Group'\CentralManagementServerNameHere\ | where {$_.Mode -ne "d"} ) 

  
$dt = Invoke-sqlcmd -ServerInstance "$($RegisteredSQLs.ServerName)" -Database "tempdb" -InputFile "D:\CMS\Scripts\T-SQL\DatabasesNotIncludedInAvailabilityGroup.sql" | out-DataTable
$dt
# Write data table to database using TVP 
$conn = new-Object System.Data.SqlClient.SqlConnection("Server=ServerWhereRepositoryDatabaseIs;DataBase=CMSRepository;Integrated Security=SSPI") 
$conn.Open() | out-null
"Connected"
$cmd = new-Object System.Data.SqlClient.SqlCommand("dbo.usp_InsertDatabasesNotIncludedInAvailabilityGroup", $conn) 
$cmd.CommandType = [System.Data.CommandType]'StoredProcedure'
#SQLParameter 
$spParam = new-Object System.Data.SqlClient.SqlParameter 
$spParam.ParameterName = "@TVP"
$spParam.Value = $dt
$spParam.SqlDbType = "Structured" #SqlDbType.Structured 
$spParam.TypeName = "DatabasesNotIncludedInAvailabilityGroup"
  
$cmd.Parameters.Add($spParam) | out-Null
$cmd.ExecuteNonQuery() | out-Null
$conn.Close() | out-Null


lcerni

Receive location of job after using Start-job command

$
0
0

Hey all so I have a script that installs software on remote machines. I've recently started using Psexec to start installing as the System account, however now I am not able to keep track of the location that Psexec is running on. The old method I could call the variable I stored the job in "$job.location" and receive the location but now when I do this I get localhost.

Here's the code:

###Software Install methods
            if($checkboxUserInstall.Checked){
                #Uses users creds to install software
                foreach($item in $computersForInstall){
                    $installArrayJobs += Invoke-Command -ComputerName $item -ScriptBlock {cmd /c "C:\Package\$($args[0])"} -ArgumentList $softwareInstallerName -AsJob -Credential $cred
                }
            }else{
                #New PsExec Install method
                $installString = { PsExec.exe "\\$($args[0])" -s -accepteula "C:\Package\$($args[1])" }
                Write-Host "Starting $($software[$index][0]) Installs.."
                foreach($item in $computersForInstall){
                    $installArrayJobs += Start-Job $installString -ArgumentList $item, $softwareInstallerName
                }
            }

I think I understand why, the top invoke command is actually invoking that command on the remote machine so it is able to keep track of the location. The bottom is using Psexec to invoke the command and cannot keep track of it. 

So long story short is there anyway I can keep track of the location while using the bottom Psexec method and the Start-Job command?

Thanks.

Remote query -Class Win32_Service does not show all services when executed by normal domain user

$
0
0

when I run the following WMI query on powershell using a domain admin user:

gwmi -query "select * from win32_service where name like 'ReportServer%' and started = 1" -computername VM-SRV-01

I got the following result:

but if you run the same using normal domain user I get nothing:

Actually when I run the following command with admin user:

Get-WmiObject -class Win32_Service

I get more services than when I run the same command with a normal domain user, and ReportServer is one of those services that appear just with admin users and disappear with normal user.

what permissions should I give SQLSrvInventoryUsr (a normal domain user) to be able to get all the services when executing the mentioned WMI queries? 



PowerShell equivelant of "netdom computername [computername] /add:computername.domain.com" ?

$
0
0

I'm adding a name to a workgroup computer, then making it the primary using this method:

netdom computername Test-app6 /add:Test-app6.contoso.local netdom computername Test-app6 /makeprimary:Test-app6.contoso.local

but wondering if there is a native PowerShell method to performing these actions? My Bing-Foo isn't turning up anything.



Question when Using A Powershell Script to Create AD Users

$
0
0

Dear all,

I want to simply my work, so I wrote a script to crreate AD users, but unfortunately it doesn't work as designed. It's the code:

Import-Module ActiveDirectory #import AD module $TempIns = Read-Host -Prompt 'Please input a user to refer' #Offer an user for reference $OU = (Get-ADUser $TempIns -Properties *).distinguishedname.substring((Get-ADUser $TempIns -Properties *).CN.length+4) #Get OU $groups = (Get-ADPrincipalGroupMembership $TempIns).name #Get groups #======================Import CSV File================================================== #[void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") #$OFDImportCSV = New-Object System.Windows.Forms.OpenFileDialog #$OFDImportCSV.ShowDialog() #$Users = Import-Csv $OFDImportCSV.FileName $Users = Import-Csv D:\ADUsers.csv #=====================End Import====================================================== foreach ($User in $Users) { #==================Define paraments================== $GivenName = ($User.'English Name' -split ' ')[0] $Surname = ($User.'English Name' -split ' ')[1] $DisplayName = $User.'English Name' $samAccountName = $GivenName+"."+$Surname $title = $User.Position $desc = $User.Position $employeeID = $User.'Employee ID' $password = $User.Password $mobile = $User.Mobile $company = $User.Company $dept = $User.Department $UPN = $samAccountName+"@microsoft.com" $Office = $User.Location $date = Get-Date #==============End definition====================== #$msg=$date + " Start create AD user " + $samAccountName Write-Output $date', Start create AD user '$samAccountName >> D:\Creation.log New-ADUser -Instance $TempIns -Path $OU -Name $DisplayName -DisplayName $DisplayName -SamAccountName $samAccountName -GivenName $GivenName -Surname $Surname -Title $title -UserPrincipalName $UPN -Company $company -Department $dept -Office $Office -ErrorVariable ADError if($ADError) { $ADError = $null Write-Output $date', Failed to created user '$samAccountName >> D:\Creation.log continue; } Set-ADAccountPassword $samAccountName -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $password -Force ) #set password Set-ADUser $samAccountName -Enabled 1 -ChangePasswordAtLogon 1 -Replace @{pager=$employeeID;Mobile=$mobile;CN=$DisplayName;sn=$GivenName} foreach( $group in $groups ) { if($group -eq 'Domain Users'){ continue; } Add-ADGroupMember $group $samAccountName } #Copy Group membership Write-Output $date', Create user '$samAccountName' successfully.' >> D:\Creation.log } #Remove-Module ActiveDirectory #exit AD module

I am really grateful if you can correct my mistakes, I am confused. Thank you in advance.


Scope a private variable

$
0
0

Hi,

Is it possible scoping a private param?

Function Execute-vctest {
[CmdletBinding()]
	Param (
		[Parameter(Mandatory=$false)]
		[ValidateNotNullorEmpty()]
		[string]$private:LogName
	)

}

execute-vctest -logname "test"
That script is just failing saying it cannot find LogName...


Last logged in user

$
0
0

I am trying to query a list of computers and get last logged in user.

First i tired wmi and found out that some or most of the clients do not have that class populated.

So i am trying to read users who logged in:

$list = gc "c:\Source\Scripts\2003.txt"
foreach
($l in $list)
      { 
 If (test-connection -count 1 $l)

            {               
  if (test-path "\\$l\c$\users")
                  {
   $strPost2003User = gci "\\$l\c$\users" |sort lastwritetime -Descending | select name -First 3 | FT
   $l; $strPost2003User
    }              
  Else
   {
    $str2003User = Get-ChildItem "\\$l\c$\documents and settings" | sort lastwritetime -Descending | select name -First 3 | FT
   Write-Host  -ForegroundColor Red $l; $str2003User
   }
            }
Else {write "$l is down"}

      }

Its working so far. I am trying to not to dispaly if user name is 'All Users'. Havng some issues with the syntax?

I think i need to change:

Write-Host  -ForegroundColor Red $l; $str2003User

If $str2003User -nq 'All Users' then dispaly......

Thanks for the help.

Need Help with for each loop using datatable

$
0
0

cls

$error.clear()

### load assembly
[Reflection.Assembly]::Load("Microsoft.SqlServer.Smo, `       
Version=10.0.0.0, Culture=neutral, `       
PublicKeyToken=89845dcd8080cc91") | Out-Null

[Reflection.Assembly]::Load("Microsoft.SqlServer.SqlEnum, `       
Version=10.0.0.0, Culture=neutral, `       
PublicKeyToken=89845dcd8080cc91")  | out-null 

[Reflection.Assembly]::Load("Microsoft.SqlServer.ConnectionInfo, `       
Version=10.0.0.0, Culture=neutral, `
PublicKeyToken=89845dcd8080cc91")  |Out-Null

Function Test-SQLConn ($Server)
{
$connectionString = "Data Source=$Server;Integrated Security=true;Initial Catalog=master;"
$sqlConn = new-object ("Data.SqlClient.SqlConnection") $connectionString
trap
{
return 0
continue
}
$sqlConn.Open()

if ($sqlConn.State -eq 'Open')
{
$sqlConn.Close();
return 1
}
}

#create hash table for end result 

#$serverinventory=@{}





#Create Connection String
$sqlConnection = new-object System.Data.SqlClient.SqlConnection "server=sqlserver;database=monitor;Integrated Security=sspi"
$sqlConnection.Open()

#Create a command object
$sqlCommandport = $sqlConnection.CreateCommand()
$sqlCommandport.CommandText = "SELECT * From monitor..Sqlports"


#Create dataset
$adapterport = New-Object System.Data.SqlClient.SqlDataAdapter $sqlcommandport
$ports = New-Object System.Data.DataTable
$adapterport.Fill($ports) | out-null


#Create a command object
$sqlCommandservername = $sqlConnection.CreateCommand()
$sqlCommandservername.CommandText = "exec Sqlservers"

#Create dataset
$adapterservername = New-Object System.Data.SqlClient.SqlDataAdapter $sqlCommandservername
$servernames = New-Object System.Data.DataTable
$adapterservername.Fill($servernames) | out-null




# Close the database connection
$sqlConnection.Close()

$ports | format-table -autosize
$servernames | format-table -autosize





foreach ($server in $servernames.rows | Out-String )

{



foreach ($port in $ports.rows | Out-String )

{

$connstring="$server,$port"
$connstring



if(Test-SQLConn $connstring -eq 1)

{
 $serverinventory.fill("$server","$port")

}

}

}

$serverinventory | format-table -autosize

  when i execute above script its displaying all servers , ports at $connstring

which should show for each servername, port

can some one help me fixing this


Powershell Command to check specific user is a part of certain group or not

$
0
0

Hi,

I need a powershell script that will check whether specific user is a part of certain group or not and if the user is part of any of those groups, script should remove it.

E.x. 

$User = "Test"

$Groups = "Group1","Group=2","Group3","Group4","Group5"

If test user is part of any of the groups from the $Groups,  it should be removed when I run the script.

Please let me know the best way to do this.

Thanks in advance


script to check last job run status

$
0
0

I want to create a script which will check if a particular job failed last night. if it failed then the job should be disabled to run next day else should run normally. 

I know a bit to write powershell command but don't know  to save it as a file and use it similar like currently I am using bat file.

Get list of SharePoint Checkout files "Microsoft.SharePoint.PowerShell" is not installed.

$
0
0

Hello - I have a SharePoint 2013 environment.  On my PC (Not the SharePoint Server) I have installed PowerShell version 3.  I was trying to use my PC and using PowerShell to get list of checked out files from our site.  I found this site http://www.falchionconsulting.com/PowerShellViewer/Default.aspx?Version=SP2010&Cmdlet=Get-SPCheckedOutFiles and tried to use Get-SPCheckedOutFiles -Sitehttp://server_name/ and message I get is the object not found (Get-SPCheckedOutFiles).  After some reading it looks like I have to useAdd-PSSnapin"Microsoft.SharePoint.PowerShell" and doing this does not work either and I getThe Windows PowerShell snap-in 'Microsoft.SharePoint.PowerShell' is notinstalled on this computer.

Does anyone can help me pointing me to the correct direction?  Do I need to be on the SharePoint server to be able to run this? Or something is not installed on my PC. 

thank you very much.


what is command or syntax for export windows 7 enterprise machines from specific OU and specific domain.

$
0
0

i am looking syntax to for following scenarios

Get-ADComputer -Filter {OperatingSystem -like "*Windows 7 Enterprise*"}|Export-Csv C:\group1.CSV -NoTypeInformation

so i am getting actual report now question is what is command or syntax for export windows 7 enterprise machines from specific OU and specific domain. concern is before doing domain or enterprise level better check the result at test OU level so please give syntax of both OU and Domain level

Exporting Event Logs to XML - Please help!

$
0
0

Hi All,

Can anyone help me out? I suspect this is something to do with the version of PS installed but its driving me crazy! I want to run a script on a remote machine to export a certain type of Event log to a xml file.

Machine 1

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

Remote machine running Windows server 2008 R2 - PowerShell version 3.0

PS > Get-Eventlog -Logname Application -ComputerName machine1 -After (Get-Date).addhours(-4) | Where-Object {$_.EventID -eq '34113'} | measure-object | Export-Clixml c:\machine1.xml

Runs fine from local machine and exports XML to c:\ without issue.

Machine 2

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

Remote machine running Windows server 2003 R2 - PowerShell version 2.0

PS > Get-Eventlog -Logname Application -ComputerName machine2 -After (Get-Date).addhours(-4) | Where-Object {$_.EventID -eq '34113'} | measure-object | Export-Clixml c:\machine2.xml

Runs then hangs and doesn’t export anything to c:\ or return any errors. However removing 'measure-object' then it runs but the export is all messed up and doesn’t give me what I need.

Both have remoting enabled and script authority set to unrestricted.

Anyone have any suggestions?

Thank you

Basic powerscript to output for loop to file and email

$
0
0

Hi 

I have this basic script that goes through a text file to ping all listed IP addresses  to see if active.

I'm trying to output the results of this script to a txt file, that I can auto email results in form of an attachment once a day.

pingsweep.ps1


Get-Content c:\IPrange2.txt | ForEach {
   # Use the Test-Connection cmdlet to determine if the machine is responding

    $pinged = Test-Connection -ComputerName $_ -Count 1 -Quiet
    # Use an If statement to determine if the machine responded or not and output accordingly
    If ($pinged) { Write-Host "$_ - OK" }
    Else { Write-Host "$_ - No Reply"}


}

I have tried to create another script to pipe the output to a file, but the file is always blank

.\pingsweep.ps1 | out-file "c:\output.txt"

or 

.\pingsweep.ps1 > "c:\output.txt"

please help, as I have spent a go while trying to figure this out.

Cheers

launching an application with a PS script

$
0
0

Hi everybody,

          I'm an absolute beginner with PowerShell, so please be patient :-)
I'm going to write my first script for PowerShell. The script core concerns an external software I need to launch. This is a typical code for a batch file:

cd case_path
echo "macro" | "app_path"app.exe case.ext 2>&1 >> log

It results in:

- go to the folder containing the 'case' to launch (just a file containing settings)
- run the case with application.exe, execute the 'internal macro' and generate a log file

I'm able to run the application with

Invoke-Item app_path\app.exe

but I can't run the specific case (and the internal macro too). Could you help me, the batch script as a starting point?

powershell folks who also use nodejs, looking for input

$
0
0

hey all - I recently had a need to bridge nodejs w/ powershell, in particular maintaining pre-established remote pssessions to o365 and then allow a program to invoke commands over those pre-established sessions (rather than restart a new shell process per command invocation which can be expensive when I need to import certain cmdlets etc)

I ended up coding this little project for this and I'd be interested in any feedback/thoughts. Hopefully this will be useful to someone else out there! https://github.com/bitsofinfo/stateful-process-command-proxy


Viewing all 21975 articles
Browse latest View live


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