Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all 6937 articles
Browse latest View live

Learning PS - Have Question Regarding Output to .txt File

$
0
0

Greetings,

First post here, so if I am violating any rules, please forgive the transgression.  

I am learning PS from a book that was given to me.  I am at the end of the first chapter and have a question about one of the labs (sounds ominous that I am only at Ch 1 and already asking for help).

The task:  Create a .txt file named mydir.txt of the C:\Windows directory.  I will place this in F:\Test

So I know I can create the desired result via the following method:

PS C:\Windows> dir > F:\Test\mydir.txt

I am trying to play around with different methods using the newer cmdlets.  Here is what I am trying:

PS C:\Windows> get-childitem | new-item -path F:\Test\ -name mydir.txt -type "file"

I know get-childitem by itself will display the entire directory on the screen.  I also know that if I use the new-item portion (obtained from the get-help new-item -examples) by itself, I can create a blank text file in the appropriate location with the specified name.

The problem I am running into is when I put the two together.  The result is that the file is successfully created in the desired directory and with the desired name, however, within the .txt file is only the very first item of the directory listing for C:\Windows.  For each subsequent item in the directory, I get the error "The File 'F:\Test\mydir.txt' already exists."

How do I get all of the get-childitem results to output into the one file?  Get-childitem seems to try and take each directory item individually and output them to it's own new-item file.  Is there a way to have it treat the directory items collectively as a "single item" for lack of a better term and put them into the single new-item file?

I hope this makes sense.  Thank you for your time,

J McKoy

 

P.S. So I had a moment of clarity right at the end of writing the big explanation above...so I just discovered that:

PS C:\Windows> get-childitem > F:\Test\mydir.txt

will also give me the desired result.  Didn't know that you could mix the old CMD commands with the new cmdlets (but now that I think about it it makes sense, since they are aliased.)  My fault in understanding seems to lie with the piping | function?  I think.  


WPF Insert Absolute Path for Resource Dictionary without using 'here-string'.

$
0
0

After much research I have discovered a way to load dynamically the required absolute path into a separate xaml Resource Dictionary file, as PowerShell seems unable to find any relative path to this file. Apparently it is possible to use the [xml] class as illustrated here:

function Add-PSScriptRoot ($file) {       #From 'Windows PowerShell In Action v2' (Payette)
   $caller = Get-Variable -Value -Scope 1 MyInvocation
   $caller.MyCommand.Definition |
      Split-Path -Parent |
         Join-Path -Resolve -ChildPath $file
}
 
$xamlPath = Add-PSScriptRoot Test-Xaml.xaml
$resource = [xml](Get-Content $xamlPath)
$dictItem = $resource.window.'Window.Resources'.ResourceDictionary.'ResourceDictionary.MergedDictionaries'.ResourceDictionary
$dictItem.Source = [string](Add-PSScriptRoot Resource.xaml)
$resource.Save($xamlPath)

$stream = [System.IO.StreamReader] $xamlPath
$form = [System.Windows.Markup.XamlReader]::Load($stream.BaseStream)
$stream.Close()
...
Is there a better way to achieve this though?

Removing an IP address using PowerShell

$
0
0

A tip that tests your knowledge about using PowerShell to remove an IP address from a network interface.

Read More 

PSTip: Use Windows Forms to generate GUI messagebox

$
0
0

While it is great that PowerShell can do so many things in the background without having to interact with it, occasionally it might be useful to have a graphical notification. For example, when a job finishes or when input is required in order for the script to be able to continue. For this purpose a popup window can be displayed; this is possible using the Windows.Forms namespace and in particular the MessageBox class.

Read More

Change Configuration Manager’s Client Cache Size with PowerShell

$
0
0

The only way to set the Configuration Manager client cache size is by specifying it at installation. This was troublesome for me as I left it the default 5GB at install, but then was requested to deploy some AutoDesk packages that where of course over that 5GB limit. Knowing I could not rely on the end user to change their cache size, I knew I had to find a better solution.

Read More

Setting the Telephone Other Properties

$
0
0

I am trying to do some bulk updating of AD accounts using set-aduser.  The fields I am having a problem with are located on the Telephones tab of ADUC. Beside each field on that tab is a button called Other.  When I run get-aduser -properties * on a user that doesn't have any of those properties set nothing appears.  However, if I manually set the Other button beside the Mobile field and run get-aduser -properties * I see othermobile appear with the data I have entered.

My question is how can I populate that field using powershell?  I have tried using the set-aduser command but I get the following error message

Set-ADUser : A parameter cannot be found that matches parameter name 'othermobile'.

Any help is appreciated.

Thanks,

Andy

Error while trying to use out-gridview with nslookup

$
0
0

Calling NSLookup in a script.  It outputs successfully to gridview but also throws the following error:

nslookup : Non-authoritative answer:

At C:\Temp\lookup.ps1:51 char:1

+ nslookup www.google.com | Out-GridView

+ ~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (Non-authoritative answer::String) [], RemoteException

+ FullyQualifiedErrorId : NativeCommandError

Any ideas on why it's complaining?

 

Thanks!

SharePoint Search Service Application Creation through PowerShell

$
0
0

Search service Application can be created and configured through Central Administration and PowerShell as well.

Read More


Run CMD Commands within a PowerShell Script

$
0
0

Sometimes when you enter commands into PowerShell they don’t execute the same way as they would in the command prompt. I ran into this issue with an uninstall string for a security software called Cylance Protect.

Read More 

query a csv file using powershell

$
0
0

I recently wrote a script that archives IIS logs into a remote server. The script runs by importing a module that mainly contains functions to copy, zip and remove files. I am populating the script the using a CSV File, which I have attached.

 The cutoffdate in the CSV represents the retention period for the IISLogs.

I do not want to run the delete action if the copy action returns an error. So, I added a column name called ActionID and PreCheckForActionID.

Later, when the script runs, for every object, I plan to add a new column in the imported CSV called results.. Hence, Before a remove action takes place, I would like to check for the PreCheckForActionID , filter the Action associated with it and check it the action was a success or returned an error.

This is what I have so far and I am completely lost, since I do not know how to go about getting the ActionID related to the PreCheckForActionID object.

 

$Newlist = Import-Csv C:\powershell\Servers.csv | Add-Member -MemberType noteproperty -Name Results -Value "success" -PassThru | Select-Object ActionID, Action, ServerName, PreCheckForActionID, Results 


$verynew = $Newlist | Select-Object -Property ActionID, Results, PreCheckForActionID | Select-Object -Property ActionID,PreCheckForActionID 


foreach($item in $verynew)
{
 $item.PreCheckForActionID

}
Here's how the CSV file looks like:
ActionID	 ServerName	 FileType	 Action	 Sourcefolder	 Destination	 Ext	 Compress	 CutOffPeriod	 PreCheckForActionID
1	A	 IISLogs	 Copy	 C$\Temp	 C:\Test\A\IISLogs	.log	 N	 	 
2	B	 IISLogs	 Copy	 C$\TEMP	 C:\Test\B\IISLogs	 .log	 Y	 	
3	C	 Backups	 Copy	 C$\Backup	 C:\Test\C\Backups	 .bak	 Y	 	 
4	A	IISLogs	Delete	C$\Temp		.log		15	1
Can someone help me out with the next step on how to correlate my PreCheckForActionID with an ActionID? 

SQL Backup via PS script

$
0
0

Greetings and Salutations!

I am a new PS scripter and am working on a backup script for some vendor servers I have inherited.  The script is run as a scheduled task every night at 01:00.

I am running into an issue backing up the SQL 2012 databases.  Below is the SQL backup portion of my script.  I get a full backup on the first of the month or whatever day I run it.  The  problem arises the next night when the script is run, I get an error that the differential cannot run because a current database backup does not exist (error code below script  snippet).

Any assistance, guidance, glances in the right direction, would be most thankfully welcome.

Thank you.

 

- Ken

 

---- Script Snippet  ----
$dom = Get-Date -UFormat %e
$srvname = gc env:computername
$root_dir = \\backup_path\
import-module sqlps -disablenamechecking
Set-Location SQLSERVER:\SQL\$srvname\DEFAULT\Databases
If ($dom -eq " 1") {
        foreach ($db in (gci)) {
        $dbname = $db.Name
        $dt = Get-Date -Format yyyyMMdd
        $sqlbufile = $root_dir + "\SQL\"+ $dbname + "\" + $dbname + "_FULL_" + $dt + ".bak"
        Backup-SQLdatabase -Database $dbname -BackupAction Database -CompressionOption On  -Backupfile $sqlbufile }
    }
Else {
    foreach ($db in (gci)) {
        $dbname = $db.Name
        $dt = Get-Date -Format yyyyMMdd
        $sqlbufile = $root_dir + "\SQL\"+ $dbname + "\" + $dbname + "_" + $dt + ".bak"
        Backup-SQLdatabase -Database $dbname -BackupAction Database -Incremental -CompressionOption On  -Backupfile $sqlbufile }
    }


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

---- Error Message ----   
Backup-SQLdatabase : System.Data.SqlClient.SqlError: Cannot perform a differential backup for database "main", because a current database backup does not exist.
Perform a full database backup by reissuing BACKUP DATABASE, omitting the WITH DIFFERENTIAL option.
At C:\folder\script-backup.ps1:122 char:3
+         Backup-SQLdatabase -Database $dbname -BackupAction Database -Incremental -Comp ...
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Backup-SqlDatabase], SmoException
    + FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.PowerShell.BackupSqlDatabaseCommand
-------------------------

Error Mounting disk image

$
0
0

When I use the "mount-diskimage" to mount a disk image (.ISO) return an error :

Mount-DiskImage : The parameter is incorrect.

+ CategoryInfo : InvalidArgument: [MSFT_DiskImage:ROOT/Microsoft/…/MSFT_DiskImage] [Mount-DiskImage], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070057,Mount-DiskImage

Note:
Get-diskimage and Unmount-diskimage also return the same error
In windows 8.1 ,I don't have this problem, I'm getting This error is only in windows 10 build 10074.

Running netsh on remote hosts

$
0
0

I'm trying to run

foreach($server in $servers){

Invoke-Command -computerName $servers -Scriptblock{

netsh int tcp set global netdma=enabled;

netsh int tcp set global dca=enabled

}

}

The command runs with no errors even returning OK after each line but no changes on the target machines when I locally run

netsh int tcp show global

PowerShell 3.0 Remoting vs PS 2.0

$
0
0

For the past few months I've been using PowerShell 2.0 with Remoting set up through Group Policy. Recently, the Microsoft Management Framework 3.0 came out as an optional update. We sent that update to our systems. Now when I want to get on to a remote computer I'm getting

[MACHINENAME] Connecting to remote server MACHINENAME failed with the following error message : The WS-Management
service cannot process the request. Cannot find the Microsoft.PowerShell session configuration in the WSMan: drive on
the MACHINENAME computer. For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (MACHINENAME:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : InvalidResourceUri,PSSessionStateBroken

 

Does PS 3.0 change the way Remoting works? I can still remote to PS 2.0 computers. I haven't done a lot of looking into this yet since it's FRIDAY.

Use a for each to insert XML data into an SQL database

$
0
0

I am trying to insert each "Program" into and SQL database.  The insert works, but it creates one row for all the "Program" objects.

This short file has three "Program" objects and the "ProgramName" field in the database will contain all three program names after the script is run.

How do I get it to insert each "Program" as a single row?

-------Script--------

$dataSource = "KEYSERVERTEST\TESTSQLSERVER"
$database = "KeyServerTest"
[xml]$programs = Get-Content shortMacList2.xml
$connectionString = "Server = $($dataSource); Database = $($database); Integrated Security = True"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString


function insert($Program)
{
$command = $connection.CreateCommand()
$command.CommandText  = "INSERT INTO InstalledPrograms (Kind, A64_Bit_Intel, ProgramName, Version, ObtainedFrom, SignedBy, GetInfoString)
 VALUES ('$($Program.Kind)', '$($Program.Intel64)', '$($Program.ProgramName)', '$($Program.Version)', '$($Program.Obtainedfrom)', '$($Program.Signedby)', '$($Program.GetInfoString)');"
$command.ExecuteReader()
}

$connection.Open()

foreach ($Program in $Programs){
    insert($Programs.ComputerProperties.Programs.Program)
}

----------Input File----------

 

<ComputerProperties>
    <ComputerName>
         computer name
    </ComputerName>
    <TimeOfLastQuery>
         4/22/2015 3:28:06 PM
    </TimeOfLastQuery>
    <Programs>
        <Program>
            <ProgramName>
                Google Search
            </ProgramName>
            <Version>
                38.0.2125.104
            </Version>
            <Obtainedfrom>
                Unknown
            </Obtainedfrom>
            <LastModified>
                4/23/15, 12
            </LastModified>
            <Kind>
                Intel
            </Kind>
            <Intel64>
                No
            </Intel64>
            <Location>
                /Users/lsmith0614/Library/Application Support/Google/Chrome/Default/Web Applications/_crx_coobgpohoikkiipiblmjeljniedjpjpf/Default coobgpohoikkiipiblmjeljniedjpjpf.app
            </Location>
        </Program>
        <Program>
            <ProgramName>
                Gmail
            </ProgramName>
            <Version>
                38.0.2125.104
            </Version>
            <Obtainedfrom>
                Unknown
            </Obtainedfrom>
            <LastModified>
                4/23/15, 12
            </LastModified>
            <Kind>
                Intel
            </Kind>
            <Intel64>
                No
            </Intel64>
            <Location>
                /Users/lsmith0614/Library/Application Support/Google/Chrome/Default/Web Applications/_crx_pjkljhegncpnkpknbcohdijeoejaedia/Default pjkljhegncpnkpknbcohdijeoejaedia.app
            </Location>
        </Program>
        <Program>
            <ProgramName>
                iMovie
            </ProgramName>
            <Version>
                10.0.6
            </Version>
            <Obtainedfrom>
                Mac App Store
            </Obtainedfrom>
            <LastModified>
                10/20/14, 1
            </LastModified>
            <Kind>
                Intel
            </Kind>
            <Intel64>
                Yes
            </Intel64>
            <Signedby>
                Apple Mac OS Application Signing, Apple Worldwide Developer Relations Certification Authority, Apple Root CA
            </Signedby>
        </Program>
    </Programs>
</ComputerProperties>


Compare two csv and create third one with a mix of columns from the two csv

$
0
0

Hi,

I need your help.

I have two csv file the first with a lot of columns and 25000 lines the second have only three columns with 1000 lines.

i need to compare the two files with only one property "usualname" it's the same column in the two files. with the  side indicator -eq == , i need to get the other propertys  location, from the first , id from the second corresponding to usualname. and finally create a 3 file with a mix of information from the two files.

$files1= import-csv -path d:\file1.csv -delimiter ","| select-object usualname,location

$files2=  import-csv -path d:\file2.csv -delimiter ","| select-object usualname,room,building,id

compare-object $file1 $file2 -property Usualname -includeequal |where {$_sideindicator -eq "=="}

then i don't have idea so i don't know what i have to do

thank you in advance for your help

regards,

youssef

replace or remove string

$
0
0

Hi All,

I need help 

$string= "tototo.titi"

i need to remove .titi 

i can get hellohellohellolqwertyazerty.titi

so i need to remove all after .*

but if i do this 

$string.replace('.*','')

it doesn't work 

Any help 

Regards,

 

Extract Attachment and Append attachment location to email

$
0
0

I have a script for copying attachments to a file folder on a server.  I need to append the attachment file path to the email body.  I am not sure how to do that.

 

Also, is it possible to delete the attachment in the email?

 

Thank you

Comparison Operators Question

$
0
0

Question on searching.   both scripts below work.  I have a .TXT file that contains all 30 NFL teams in alphibetical order.  If I run the first script and I
search for -like '*New"' it will return

The team you are seeking:   New England Patriots
The team you are seeking:   New Orleans Saints
The team you are seeking:   New York Giants
The team you are seeking:   New York Jets


# Script 1
$nfl = Get-Content "c:\temp\nfl.txt"
foreach ($team in $nfl) { IF ($team -like '*New*') { Write-Host "The team you are seeking:  " $team}}


but with script 2 below using -like and -contains don't work.  I had to use -match.  Why?  How is using READ-HOST different than Script 1 ?

# Script 2
$Find = Read-Host "Enter part of the team name"
$nfl = Get-Content "c:\temp\nfl.txt"
foreach ($team in $nfl) { IF ($team -match $Find) { Write-Host "The team you are seeking:  " $team}}

Disable multiple AD account through PowerShell

$
0
0

I need to disable a long list of users, and I'm wondering if anyone can advise me on how to create a Powershell script that would do this from a list of users in a text file, etc.

Here's a few details about the users:
- The info on our term list identifying the users to be disabled is first and last name, as opposed to user ID, distinguished name, etc.
- Sometimes the first or last name may not match what is listed in AD.  For example, someone may be in AD under their first name, but actually uses their middle name, ans that's what is listed on the term list.
- Sometimes when I search for someone (first and last name), it will come up with more than one account that has either the same or similar name, and I will need to figure out which one needs to be disabled.  For example, there may be 2 Bob Smith users, one of which is bob.smith1, the other being bob.smith2.

Some info about what I usually do when disabling terminated users:

- Disable the account
- Reset the password (can be the same complex random pw)
- Clear the manager field under the Organization tab
- Remove the user from all groups except Domain Users
- Move the user account to a Disabled Users OU 

I also do the following in the Exchange Console:
- Check the "Hide from Exchange address lists" box on the General tab
- Disable all features on the Mailbox Features tab

Sometimes a user I need to disable is partially disabled, so I want to make sure that if I run a script to do all of this, the step that disables a user account will not toggle it to enabled if it is already disabled.  The same is true for hiding the user's mailbox from the exchange address lists.  I also need to make sure that (for example) if more than one user account is found, it doesn't make any changes to the incorrect user.  I would be fine with receiving prompts while the script runs, or even just a list of names that were skipped due to errors, and I can disable those manually.

Please let me know if you have any questions, and thanks in advance for the help.

Andrew

Viewing all 6937 articles
Browse latest View live