Quantcast
Channel: PowerShell General
Viewing all 10624 articles
Browse latest View live

Missing DnsServer module and get-DNSServerResourceRecord

$
0
0

I am trying to leverage the get-DNSServerResourceRecord that comes with Powershell 4.0.  On my windows 7 machine, the IT staff (I am not local admin on my machine) has installed WMF 4.0 and RSAT and enabled the latter under the Control Panel.  I can see the tools, particularly the DNS mmc under the start menu.  When I attempt to use it within powershell, I get "get-dnsserverresourcerecord is not recognized as the name of a cmdlet"

It seems missing from the list of available modules:

    Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.0.0.0    ActiveDirectory                     {Get-ADRootDSE, Ne..
Manifest   1.0.0.0    AppLocker                           {Set-AppLockerPoli..
Manifest   1.0.0.0    BitsTransfer                        {Add-BitsFile, Rem..
Manifest   1.0.0.0    CimCmdlets                          {Get-CimAssociated..
Manifest   1.0.0.0    FailoverClusters                    {Add-ClusterDisk, ..
Manifest   1.0.0.0    GroupPolicy                         {Backup-GPO, Copy-..
Script     1.0.0.0    ISE                                 {New-IseSnippet, I..
Manifest   3.0.0.0    Microsoft.PowerShell.Diagnostics    {Get-WinEvent, Get..
Manifest   3.0.0.0    Microsoft.PowerShell.Host           {Start-Transcript,..
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Content, Clea..
Manifest   3.0.0.0    Microsoft.PowerShell.Security       {Get-Acl, Set-Acl,..
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Format-List, Form..
Manifest   3.0.0.0    Microsoft.WSMan.Management          {Disable-WSManCred..
Manifest   1.0.0.0    NetworkLoadBalancingClusters        {Add-NlbClusterNod..
Binary     1.0        PSDesiredStateConfiguration         {Set-DscLocalConfi..
Script     1.0.0.0    PSDiagnostics                       {Disable-PSTrace, ..
Binary     1.1.0.0    PSScheduledJob                      {New-JobTrigger, A..
Manifest   2.0.0.0    PSWorkflow                          {New-PSWorkflowExe..
Manifest   1.0.0.0    PSWorkflowUtility                   Invoke-AsWorkflow
Manifest   1.0.0.0    TroubleshootingPack                 {Get-Troubleshooti..

What do I need to do to use this new cmdlet?


Report of members of local Administrators group

$
0
0

I found this here: (http://powershell.com/cs/media/p/376.aspx)

  1. cls 
  2. $ErrorActionPreference="SilentlyContinue" 
  3. Get-Content (ENTER PATH TO YOUR INPUT FILE HERE) | foreach
  4.     [ADSI]"WinNT://$_/administrator" | select ` 
  5.     $(Name="Account";Expression={($_.PSBase).Path}}, ` 
  6.     $(Name="Password Set";Expression={(Get-Date).AddSeconds(-($_.PasswordAge)[0])}}; ` 
  7.     $(Name="PasswordAge (Days)";Expression={[int]((4-.PasswordAge)[0]/86400) }}, ` 
  8.     $(Name="Last Logon";Expression={$_.LastLogin}}, ` 
  9.     $(Name="Days Since Last Logn";Expression={ ` 
  10.     (New-TimeSpan-start ($_.LastLogin[0]) -end (Get-Date)).days}}} ` 
  11. | Export-csv (ENTER PATH TO YOUR OUTPUT FILE HERE) -notypeinformation 

The $'s in the SELECT statement need to be @'s... That corrected, I'm trying to get to run so I can report on the local administor account - by SID.  Our local admin accounts are renamed depending on department.   Also to run against all (local account) members of the builtin administrators group.

I've been able to dump the members, but am having trouble putting the two halves together.  

 

The given path's format not supported

$
0
0

Hi gurus

  I am learning PS so go easy on me.

I have the following simple lines but is giving me problems

$filetobecopy="c:\computer.txt"

$filedestination="c:\temp\"

$PC="60.56.23.45"

copy-item $filetobecopy -Destination \\$PC\c$\$filedestination

and it gives me the "The given Path's format is not supporter"

can someone help me please.

 

Thanks a bunch

 

help with filezip

$
0
0

I have a folder with a number of IIS Logs. I would like to zip and archive the IIS logs I do not want to archive everything in 1 zip folder. As a matter of fact, I would like to create 1 zip folder per log and would like the folder to have the same basename as the log file.

I am trying to use this function to achieve what I want:

function add-zip{
param($source, $destination)

$name = Get-ChildItem $source | Select-Object basename

foreach($obj in $name)
{
Add-Type -Assembly System.IO.Compression.FileSystem
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
$zipfilename = $destination + "\" + $obj.BaseName + ".zip"

[System.IO.Compression.ZipFile]::CreateFromDirectory("$source\$name",
$zipfilename, $compressionLevel, $false)

}
}

Using the function, I was able to get the zip folders to have the same name as the IIS logs themselves. However, all the zip files present at the source folder got copied inside every zip folder. How do I make sure that every zip folder only gets 1 log file?
I would appreciate the help.

Thanks

help with powershell logon script

$
0
0

Hi all,

I need assistance in powershell logon script to run powershell console with administrative privileges for non admin accounts.

Currently below is my logon script but some how i couldn't change my wallpaper of users logging into workstation. I feel because of console not have privilege 

#setting disablefirstwizard settings

Set-itemproperty -path HKLM:\software\Microsoft\windows\internet explorer\main -name disablefirstwizard -value 1

#setting of wallpaper

Set-itemproperty -path HKCU:\Control Panel\Desktop -name wallpaper -value C:\windows\.bmp

rundll32.exe user32.dll, updateperusersystemparameters

Is there a possibility to set console environment so that rest of script will be running under user specified at top irrespective of logged in user(Guest).

$user = "test"

$password = "password"

#setting disablefirstwizard settings

Set-itemproperty -path HKLM:\software\Microsoft\windows\internet explorer\main -name disablefirstwizard -value 1

#setting of wallpaper

Set-itemproperty -path HKCU:\Control Panel\Desktop -name wallpaper -value C:\windows\.bmp

rundll32.exe user32.dll, updateperusersystemparameters

 

Please let me know if i need to add more information.

Thanks in advance.

thanks,

Vamsi

Adjusting visual effects using powershell

$
0
0

I am creating a bunch of windows servers in my organizations private cloud. One problem i noticed that all of those servers have System-->Advanced Settings-->Advanced-->Performance Setting-->Visual Effect set to 'Adjust for best appearance' which makes the server very slow> I want to reset that to 'Adjust for best performance' using powershell.

I tried using below option to change that in registry, it sets the option as expected but the change doesnt come into effect either with a log off or a reboot.

$path = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects'

try {

    $s = (Get-ItemProperty -ErrorAction stop -Name visualfxsetting -Path $path).visualfxsetting 

    if ($s -ne 2) {

        Set-ItemProperty -Path $path -Name 'VisualFXSetting' -Value 2  

        }

    }

catch {

    New-ItemProperty -Path $path -Name 'VisualFXSetting' -Value 2 -PropertyType 'DWORD'

    }

Any thoughts about this?

Date Time formating changes in script

$
0
0

I have a bigger script that has a section like this in it were I ask each DC for the last login and convert it to a readable format and I think formatting is the issue but I don’t know how to solve it.

 

$DC01=Get-ADUser $_.SamAccountName -Serverdc01-PropertiesLastLogon|Select-Object @{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}} |Select-Object-ExpandPropertyLastLogon

$DC02=Get-ADUser$_.SamAccountName -Serverdc02-PropertiesLastLogon|Select-Object @{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}} |Select-Object-ExpandPropertyLastLogon

$DC03=Get-ADUser$_.SamAccountName -Serverdc03-PropertiesLastLogon|Select-Object @{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}} |Select-Object-ExpandPropertyLastLogon

$DC04=Get-ADUser$_.SamAccountName -Serverdc04-PropertiesLastLogon|Select-Object @{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}} |Select-Object-ExpandPropertyLastLogon

 

If I now check that data and manipulate it I get the following

PS U:\> $dc01

20 April 2015 16:20:46

 

PS U:\> $dc02

22 April 2015 08:39:03

 

PS U:\> $dc03

17 April 2015 15:32:07

 

PS U:\> $dc04

22 April 2015 08:14:11

 

I like the format 22 April 2015 08:14:11 and want to keep it like that

 

If I now add them to a variable the format changes to American date format of MM/DD/YYYY HH:MM:SS. I want to either keep is as 22 April 2015 08:14:11 or have UK format of DD/MM/YYY  HH:MM:SS.  The server I’m running this on has it’s region set to UK

 

$LastTrueLogon="$dc01","$dc02","$dc03","$dc04"

PS U:\> $LastTrueLogon

04/20/2015 16:20:46

04/22/2015 08:39:03

04/17/2015 15:32:07

04/22/2015 08:14:11

 

$LastTrueLogon | Sort-Object | Select-Object -Last 1

04/22/2015 08:39:03

 

It is because a report is being generated for the service desk and it confuses them, I removed the times in the text below to compact it down (It still doesn't line up in the post), but I want to retain it in my report

 

DisplayName            SamAccountName    EmployeeNumber    DC01                        DC02                        DC03                        DC04                        LastTrueLogon

Young, Sarah            casepsy                    32081A                    05/12/2014             13/07/2014             28/08/2014             05/12/2014                12/05/2014

Changing Network Priority Stack Order

$
0
0

In a Windows 7 environment, all of our laptops are coming out imaged with the Network connections listed in order as follows:  Local Area Connection 2, Wireless Network connection, Local Area Connection. This creates a problem when our laptop users are on their docking station, they are staying connected to the Wireless, when we want them on the Ethernet while on the dock.

To manually change the order of the stack, I can go to Control Panel > Network and Sharing Center > Change Adapter Settings > Advanced > Advanced Settings > and with the green up arrows, i can move Local Area Connection to the top followed by Local Area Connection 2, then wireless last.

I have over 200 laptops on the network and I was wondering if there was a script I could use to automate this process.


Merging two columns in a CSV

$
0
0

Merging two columns in a CSV to make a third

$objs=@();

$output=Import-csv-Path"U:\Abook1.csv"|ForEach {

$Object=New-ObjectPSObject-Property @{           

        CN  =[String]::Concat($_.Surname,$_.Firstname)

        Firstname=$_.firstname

        Surname=$_.Surname

        PersonalRef=$_.PersonalRef          

    }  

    $objs+=$Object;

}

$objs

$objs|Export-CSvU:\LeaversFeb2015.csv

 

Outputs this

CN                          Firstname            PersonalRef       Surname

HallJonathan      Jonathan             1234156                Hall

I need CN to be Hall, Jonathan so how to I add the separator to

CN  =[String]::Concat($_.Surname,$_.Firstname)

adding wpf external on powershell

$
0
0

Hi Team,

I am creating an application for my work, but the only resources that I got is the built in powershell ISE from my desktop. I was able to do some applications for my co-leagues @ work using powershell + WPF. Now I am planning to create new application but this time I want to use EXTERNAL FILE for my <resourcedictionary>. But I spent a month (honestly) figuring out how to do it but I got none. I do believe powershell + WPF can do a Slick app. Please help me how to make it possible.

 

Here is my code #####

#build the GUI

Clear-host

cd "D:\powershell\Lesson\metro\"

Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase,system.windows.forms

[xml]$xaml = @"

<Window

   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    WindowStartupLocation="CenterScreen" Name="Main"

    Width="800" Height="700" ShowInTaskbar="True">

        <Window.Resources>

                            <ResourceDictionary Source="sample.xaml" />     

        </Window.Resources>

</Window>

"@

$reader = (New-Object System.Xml.XmlNodeReader $xaml)

$Window = [Windows.Markup.XamlReader]::Load($reader)

$Window.ShowDialog()

Here is the error ###############################################

Exception calling "Load" with "1" argument(s): "'sample.xaml' value cannot be assigned to property 'Source' of object 'System.Windows.ResourceDictionary'. Cannot locate resource 'samp

le.xaml'.  Error at object 'System.Windows.ResourceDictionary'."

At D:\powershell\Lesson\metro\Basic_WPF.ps1:20 char:44

+ $Window = [Windows.Markup.XamlReader]::Load <<<< ($reader)

    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

    + FullyQualifiedErrorId : DotNetMethodException

I hope someone can help about this. Thanks Team.

powershell excel search replace issue with loop

$
0
0

What I'm doing here is to search excel sheet for a value, if value matches it will be replaced by first value in a given text file:

example:

search for value text find the first instance replace with first value in a given text file which is "read", search again for text find again replace with "read" until can't find "text", now search for second value in array "text1", search in excel sheet find it replace with second line in given text value, which is "read1" and so on.

I have the script that is working somewhat, issue is it will replace all array values with only first line of text file which is "read", it is not looping through the second line of text file.

 

Can someone please help.

code:

test.txt file read as:

read

read1

read2

 

$text="text","text1","text2","text3"$replace=get-contentC:\script\test.txt$File="C:\script\test.xlsx"# Setup Excel, open $File and set the the first worksheet$i=0$Excel=New-Object-ComObjectExcel.Application$Excel.visible=$true$Workbook=$Excel.workbooks.open($file)$Worksheets=$Workbooks.worksheets$Worksheet=$Workbook.Worksheets.Item(1)$Range=$Worksheet.Range("A1","Z10").EntireColumnForeach($SearchStringin$text){$Search=$Range.find($SearchString)if($search-ne$null){$SearchString$replace[$i]$FirstAddress=$search.Addressdo{$Search.value()=$replace[$i]$search=$Range.FindNext($search)}while($search-ne$null-and$search.Address-ne$FirstAddress)$i++}}$WorkBook.Save()$WorkBook.Close()[void]$excel.quit()

Local admin list with info for account

$
0
0

Howdy

I found a script on here that I think I am close to getting to work for what I need. But I am stuck on the for-each loop for the list of computers I need to run it against and saving the output to a file.

Here is what I have so far:

Hi Jaap,

I've made it this far and I get the results for only 1 computer in the list...Can you help me out please?

 

Get-Content c:\temp\computers.txt | ForEach-Object {

$computername = $_

$localGroupName = "Administrators"

$group = [ADSI]("WinNT://$computerName/$localGroupName,group")

$group.Members() |

    foreach {

        $AdsPath = $_.GetType().InvokeMember('Adspath', 'GetProperty', $null, $_, $null)

        $a = $AdsPath.split('/',[StringSplitOptions]::RemoveEmptyEntries)

        $name = $a[-1]

        $domain = $a[-2]

        $Sid = $_.GetType().InvokeMember('objectsid', 'GetProperty', $null, $_, $null)

        # Ignore non-local accounts

       # if ($domain -eq $computerName)

            New-Object -TypeName PSObject -Property ([ordered]@{

                Name = $name;

                Computer = $computerName;

                PasswordAge = [int]((([ADSI]"WinNT://$($computerName)/$($name)").passwordage[0])/86400)

                objectSid = (New-Object System.Security.Principal.SecurityIdentifier($Sid, 0)).Value

            })

        }

    }

-filter and where

$
0
0

Hi All,

I am very new to powershell and it is just days I started learning it. I have some idea on batch scripting. I am confused when should I use -filter command and where(or where-object) commands. What is the main difference  and when should we use -filter and where commands. For ex, in this command,

Get-Process | Where-Object {$_.handles -gt 200}
why can't I use get-process -filter handles -gt 200

 

Chaitanya.

get-wmiobject - the rpc server is unavailable - timeout issue

$
0
0

Hi,

I am doing a WMI query within my script, and random servers keep timing out and jumping into the CATCH portion of the Try/Catch and not every time I run it either.

Try {
$Service = Get-WmiObject -Class Win32_Service -ComputerName $Computer -EnableAllPrivileges -ErrorAction Stop | Select Caption, State, PathName | ? {$_.PathName -like "*sqlservr.exe*" -and $_.Caption -notlike "*$*" -and $_.Caption -notlike "*#*"}
}
Catch{
write-host "WMI Connection Failed   $error[0]"

However after the script finishes, I test these servers' WMI and it responds.

Turns out the failure is due to a Timeout. WMI querry takes too long and powershell drops it with The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) Timeout expired.

Is there any way to extend the timeout period of the query?

 

Thank you,

Russ

 

 

 

 

Introduction to Using the PowerShell Command Line with DB2 on Windows

$
0
0

I have worked with DB2 on Windows on and off over the years and have largely not enjoyed it all that much. Most likely because the vast majority of my time is spent on UNIX and Linux systems, so when I end up at a windows command line, my fingers type things like “ls” and “grep” before I can even stop them. I think this is a common condition for DB2 consultants and DBAs – most of us spend the majority of our time on Linux or UNIX or even both and then have to jump into a Windows system and still be proficient.

Read More


PowerShell Past and Future with Lee Holmes

Start Dynamics NAV Windows Client (RTC) from PowerShell

$
0
0

After my sessions during “conference season”, I promised to blog about my scripts. I decided to do this on small pieces of scripts .. and this one is so useful, though I only realised it was useful until I wanted to do a gimmick during a script. I’m actually using it all the time now :-).

Read More

PowerShell Problem Solver: How to Pull Data from Log Files using PowerShell

$
0
0

If the log files are structured or predictable, it doesn’t take much to create a PowerShell tool for extracting useful information. Many times you can get what you need with a simple one-line command. If this is a process that’s worth repeating or something you have to entrust to someone else, then you’ll want create a re-usable tool. In this article, I’ll show you how to easily pull data from log files using PowerShell, with some additional help from the Get-Content and Import-CSV cmdlets.

Read More

Easy way to Configure your Powershell Profile

$
0
0

Powershell was most widely used in all the latest version of the windows operating system. There are so many uses of the powershell commands and powershell scripting that make you simplify the work such as customization, automation, scheduling etc. From the windows 7 operating system powershell has been introduced as an inbuilt component. You can also use the powershell in the windows xp operating system but you should manually download the package and install it in the windows xp.

Read More

How To Automate File Hash Check With PowerShell

$
0
0

hash checking allows you to ensure that the files you copy are 100 percent the same. When copying hundreds or thousands of files, you can automate file hash check with PowerShell -- here's how.

Read More

Viewing all 10624 articles
Browse latest View live


Latest Images