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

Copy files to the destination's sub-folders only while excluding specific sub-folders. PS or batch

$
0
0

So I have danced with this off and on throughout the day and the timeless phrase "There's more than one way to skin a cat" keeps coming to mind so I decided to take to the community.

Scenario:

Source folder "C:\Updates" has 100 files of various extensions that need to be copied to thesub-folders only of "C:\Prod" and overwrite any duplicate filesif they exist.

The Caveats:

  1. The destination folder names in "C:\Prod" are quite dynamic and change frequently.
  2. A naming convention is used to determine which sub-folders in the destination need to be excluded when the source files are being copied (retaining the original version of the files).  For ease of explanation lets say any folder names starting with"!stop" should be excluded from the copy process. (!stop* if wildcards considered)

So, here I am wanting the input of those greater than I to tackle this in PS if I'm lucky.  I've tinkered with Copy-Item and xcopy today so I'm excited to hear other's input.

Thanks!

-Chris





Trouble getting AD Update from CSV script to work

$
0
0

Hello, 

I am trying to get a script up and running that will check to see if the user in the CSV exists, and if so then run the update command, and if not then run the new user command.  I believe that my flaw is in the logic of the if/then statements. 

I am very new to powershell so please forgive me if this is answered elsewhere but I searched and could not find an answer.  

Current script:

# Import AD Module             
Import-Module ActiveDirectory            

write-Host 'Starting to update AD Attributes.......' -NoNewline -ForegroundColor Yellow            
# Import CSV into variable $users           
      
$users = Import-Csv -Path "C:\Users\Administrator\Desktop\AD Management\AD-Users-Test.csv"            
# Loop through CSV and update users if the exist in CVS file            
            
foreach ($user in $users) {            
#Search in specified OU and Update existing attributes            
 IF (Get-ADUser $($user.samaccountname)) {Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" -Properties * -SearchBase "DC=waiconnor,DC=net"|            
  Set-ADUser -DisplayName $($user.DisplayName) -UPN $($user.UPN) -GivenName $($user.GivenName) -Surname $($user.Surname) -name $($user.name) -Description $($user.Description) -Office $($user.Office) -OfficePhone $($user.OfficePhone) -Email $($user.Email) -Street $($user.Street) -City $($user.City) -State $($user.State) -PostalCode $($user.PostalCode) -Fax $($user.Fax) -Company $($user.Company) -Department $($user.Department) -Title $($user.Title) -Info $($user.Info) -ProfilePath $($user.ProfilePath)
  }
  Else {New-ADUser -DisplayName $($user.DisplayName) -userPrincipalName $($user.userPrincipalName) -GivenName $($user.GivenName) -Surname $($user.Surname) -name $($user.name) -Description $($user.Description) -Office $($user.Office) -OfficePhone $($user.OfficePhone) -Email $($user.Email) -Street $($user.Street) -City $($user.City) -State $($user.State) -PostalCode $($user.PostalCode) -Fax $($user.Fax) -Company $($user.Company) -Department $($user.Department) -Title $($user.Title) -ProfilePath $($user.ProfilePath)
  }
}

Write-Host 'done!' -ForegroundColor Green

Remotely enable PSRemoting

$
0
0

Hi guys,

So, the scripting world is new to me but I’m trying to get a handle on it, and hope that you can help me.

I’m working in a mixed environment; our domain contains XP clients and 2008R2 servers. All client computers have PS 2.0 installed.

I want to be able to work with PSRemoting on other client computers. Of course I have Admin privileges and I ran the commands as admin.

My problem is that I can't enable remoting through Group Policy. Our organization is really big and changing GPO will take forever because of IT policies and different approvals.

Right now we have a few jobs we really need to execute and can’t wait till GPO changes are done.

So actually, I’m looking for a way to enable remoting on remote machines in our domain. When I logon interactively to a machine and enable PSReomting, I’m able to work remotly on this machine after that. But I can't find a way to remotely enable PSReomting.

I’ve tried to enable thewinrm service through cmd, and then with PS, like this:

SC\\server start winrm

Then, from PS:

foreach ($i in 'Computer') { Enable-PSRemoting -Force }

Then I ranwinrm quickconfig, and the result was:

WinRM already is set up to receive requests on this machine

WinRM already is set up for remote management on this machine

After performing these steps, I tried remoting and got this error:

"Connecting to remote server failed with the following error message: access is denied. for more info...."

I went through every step in About_Remote_Troubleshooting but found nothing.

After googling for hours I found nothing.

Also, does anyone know if PS Active Directory module is available for XP? After some searching it looks like XP doesn’t support this module, but just to make sure.

Thank youJ

Set-HgsClientConfiguration Fails with InsecureHostConfiguration error

$
0
0

Hi

I have a Host Guardian Server running correctly, with the following status:

PS C:\Users\Administrator.EXC> Get-HgsServer

Name                           Value
----                           -----
AttestationOperationMode       AD
AttestationUrl                 {http://hgs4.exc.dc/Attestation}
KeyProtectionUrl               {http://hgs4.exc.dc/KeyProtection}

Detailed diagnostics are as follows:

PS C:\Users\Administrator.EXC> Get-HgsTrace -RunDiagnostics -Detailed
Overall Result: Pass
    WIN-P54TEDPBAGD: Pass
        HGS Service Configuration: Pass
            Code Integrity Policies Installed: NotApplicable
            Baseline Policies Installed: NotApplicable
            Authorized Hosts Added: NotApplicable
            Authorized Host Groups Added: Pass
        Hardware: Pass
            Provisioned Memory: Pass
            Memory Usage: Pass
        HTTPS: Pass
            Key Protection Administration Certificate Validation: NotApplicable
            Bindings without SSL Certificates: NotApplicable
            Attestation Server Certificate Subject Verification: NotApplicable
            Key Protection Server Certificate Subject Verification: NotApplicable
        Certificates: Pass
            KPS Certificate Permissions: Pass
            Attestation Certificate Permissions: Pass
            Attestation Signing Certificates Valid: Pass
            Attestation Signing Certificates Registered: Pass

When I try to attest a host with this service, I get the following:

PS C:\Users\Administrator> Set-HgsClientConfiguration -KeyProtectionServerUrl "http://hgs4.exc.dc/KeyProtection" -AttestationServerUrl "http://hgs4.exc.dc/Attestation"


IsHostGuarded            : False
Mode                     : HostGuardianService
KeyProtectionServerUrl   : http://hgs4.exc.dc/KeyProtection
AttestationServerUrl     : http://hgs4.exc.dc/Attestation
AttestationOperationMode : ActiveDirectory
AttestationStatus        : InsecureHostConfiguration
AttestationSubstatus     : VirtualSecureMode

Further details are:

PS C:\Users\Administrator> Get-HgsTrace -RunDiagnostics -Detailed
Overall Result: Fail
    WIN-3LNHGUEVMU7: Fail
        Test Attestation: Fail
            Check Attestation Status: Fail>>> The host cannot attest because virtual secure mode could not be detected.  Please ensure that the>>> Isolated User Mode feature is installed and enabled, and that this is a physical machine (not a virtual>>> machine).
        HGS Client Configuration: Pass
            Code Integrity Policy Installed: NotApplicable
            Code Integrity Policy Active: NotApplicable
            Attestation Service Responds to Requests: Pass
            Key Protection Service Responds to Requests: Pass
            Valid VSM IDK Detected at Boot: NotApplicable
        Hardware: Fail
            Secure Boot: DependencyFailed
                UefiHardwareProfileCollector: Exception>>> Could not read the UEFI variable "SecureBoot".  This usually indicates a lack of administrator>>> privileges or a host that utilizes a legacy BIOS.  If you have sufficient privileges and are on a>>> UEFI-enabled host, verify you have the latest version of the manufacturer's firmware and drivers.>>> You may need to run this locally if the cmdlet was called remotely.
            Full Boot: NotApplicable
            TPM Presence: NotApplicable
            TPM Version: NotApplicable
            UEFI Setup Mode: DependencyFailed
                UefiHardwareProfileCollector: Exception>>> Could not read the UEFI variable "SecureBoot".  This usually indicates a lack of administrator>>> privileges or a host that utilizes a legacy BIOS.  If you have sufficient privileges and are on a>>> UEFI-enabled host, verify you have the latest version of the manufacturer's firmware and drivers.>>> You may need to run this locally if the cmdlet was called remotely.
        HTTPS: Pass
            Attestation Server Certificate Verification: NotApplicable
            Key Protection Server Certificate Verification: NotApplicable
        Network: Pass
            HGS Servers Reachable: Pass
            DNS Servers Reachable: Pass
            Resolves Service Hostname: Pass
            Service Hostname Resolves the Same on All DNS Servers: Pass
        Best Practices: Warning
            Local Mode: Pass
            Resolves Service Hostname to Multiple Addresses: Warning>>> DNS server at 192.168.2.110 cannot resolve "hgs4.exc.dc" to multiple IP addresses.  The recommended>>> configuration is to have multiple HGS servers available at "hgs4.exc.dc" for high availability.

My understanding is that this error should not appear since I am performing AD based attestation, and virtual secure mode should not be needed in this case. Kindly suggest resolution. If more information is needed to solve this, then where should I check?

Thanks in advance

Zawar

Confuse about powershell validatescript

$
0
0

function test{
    param(
        [ValidateScript({$_ -is [System.Object[]]})]
        $a=@()
    )

    $a
}



function test2{
    param(
        [ValidateScript({$_ -is [System.Collections.Hashtable]})]
        $a=@{}
    )

    $a
}

test -a @(1,2,3)
test2 -a @{a=1;b=2} 

test : 无法对参数“a”执行参数验证。值为“1”的参数的“$_ -is [System.Object[]]”验证脚本未返回 True 结果。请确定验证脚本失败的原因,然后重试该命令。
所在位置 行:21 字符: 9
+ test -a @(1,2,3)
+         ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [test],ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,test


Name                           Value                                                                                 
----                           -----                                                                                 
a                              1                                                                                     
b                              2  

how can i using validatescript to validate a param is an array?

       

yoke88
IM:yoke-msn@hotmail.com

PowerShell ISE - NuGet-anyCPU Initialization Failed

$
0
0

I installed the module browser for the ISE but am unable to browse modules on the PowerShell gallery. 

When launching the ISE I receive a message indicating that the module browser requires NuGet-anycpu.exe to interact with NuGet based galleries. Shortly after clicking the Accept button I receive a message that "Initialization failed. Unable to find package provider 'NuGet'.

Any ideas on how to get past this?

I've tried the following:

- Setting 32-bit and 64-bit execution policies to unrestricted
- Launching ISE as administrator
- Successfully installed the NuGet provider via Install-PackageProvider -name NuGet -Force

how to replace html table

$
0
0

Hi, I have a html file that I would like to update a particular table every once in awhile. The old table should just be replaced with the new one as the no. of row items change over time. Can someone advice how can this be achieved in powershell?

Thanks

Add-PsSnapin takes very long

$
0
0

Hello,

I have a script which works fine, only the time to load the SharePoint PS SnapIn is to long.

How can I do load the PS SnapIn faster ?

Script:

Start-Transcript 'c:\temp\log.txt'
try{
	$start_time = (Get-Date)
    write-host "Loading SharePoint Powershell Snapin"
	If ((Get-PsSnapin |?{$_.Name -eq "Microsoft.SharePoint.PowerShell"})-eq $null)
		{ $PSSnapin = Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Out-Null }

	$finish_time = (Get-date)
	$installation_time = New-TimeSpan -Start $start_time -End $finish_time
	$installation_time_m = $installation_time.Minutes
	$installation_time_s = $installation_time.seconds

	Write-Host "The installation takes"$installation_time_m "minute(s) and"$installation_time_s "secound(s)."

	$Server = get-spserver
	write-host $server

	write-host "FINSIH"
}
catch{
	Write-Host "ERROR"
}
finally{
	Stop-Transcript
	}

Log:

**********************

Windows PowerShell Transcript Start

Start time: 20140424125607

Username  : …

Machine           : ZMUC. (Microsoft Windows NT 6.1.7601 Service Pack 1)

**********************

Transcript started, output file is c:\temp\log.txt

Loading SharePoint Powershell Snapin

 

Takes 1 minute(s) and 6 secound(s).

 

SPServer Name=ZMUC… SPServer Name=zmuc…

FINSIH

**********************

Windows PowerShell Transcript End

End time: 20140424125713

**********************

I hope somebody can help me,


Thanks Horst MOSS 2007 Farm; MOSS 2010 Farm; TFS 2010; TFS 2013; IIS 7.5


Not able to send email thru Outlook

$
0
0

Hello

I am using following code to send email thru Outlook.  I want to send it thru Outlook Client only. I am working on 64 bit machine with OutLOok 2010. I know that I can send it thru smtpserver option in a diferent way, but my client wants to send it thru OutLook client.

$outlook = New-Object -comObject  Outlook.Application  
$mail = $outlook.CreateItem(0)  
$mail.Recipients.Add($recipientEmail)  
$mail.Subject = $subject  
$mail.Body = $body         
$mail.Send()  
Write-Host "Email sent!"

I am getting following error, can anyone tell me what wrong I am doing

New-Object : Retrieving the COM class factory for component with CLSID

{0006F03A-0000-0000-C000-000000000046} failed due to the following error:

80080005 Server execution failed (Exception from HRESULT: 0x80080005

(CO_E_SERVER_EXEC_FAILURE)).

At line:1 char:12

+ $outlook = New-Object -comObject  Outlook.Application

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

    + CategoryInfo          : ResourceUnavailable: (:) [New-Object], COMExcept

   ion

    + FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Comman

   ds.NewObjectCommand

You cannot call a method on a null-valued expression.

At line:2 char:1

Computer Data into 1 csv file ?

$
0
0

Hi

(Newish to PS)

I have created a PS script, to collect various bits of data and put it into a csv file , but now there are too many csv files, so I'd like to have one csv file with all the computer related data.  

Currently Im getting various reports, such as $computername.DiskReport.csv, $computername.SystemReport.csv, Id like these to be in one csv file based on the server, so computer1.csv computer2.csv etc.

(I'm not looking for anyone to write my script for me, but I need some suggestions or simple to follow samples on how I can achieve this).

this is my current code on getting the data, which I have got from the Script Repo etc

In summary:

1.I create a file in my path

2. I have a server list which contains the server names

3. The Functions are called (Get-WmiObject win32_logicaldisk  and gwmi -query "select * from
       Win32_ComputerSystem) see below. I get the data, which is logged into the csv file, so all good there. 

****FUNCTION CODE STARTS HERE***

Function MyGetDiskInfo {

 Clear-host
 $ServerListFile = "$MyPath\server_list.txt" 
 $ServerList = Get-Content $ServerListFile -ErrorAction SilentlyContinue
  ForEach ($computername in ($ServerList)) 
   {Get-WmiObject win32_logicaldisk -ComputerName $computername  -Filter "Drivetype=3" `
     | Select DeviceID, Drivetype, FreeSpace, Size, VolumeName |
        Export-Csv -path "$MyPath\$computername.DiskReport.csv" -NoTypeInformation
   }
  
}

 #Create System Info Report CSV File

 Function MyGetSysInfo {

 Clear-host
 $ServerListFile = "$MyPath\server_list.txt" 
 $ServerList = Get-Content $ServerListFile -ErrorAction SilentlyContinue
  ForEach ($computername in ($ServerList)) 
   {gwmi -query "select * from
       Win32_ComputerSystem" -computername $computername | select Name,
       Model, Manufacturer, Description, DNSHostName,
       Domain, NumberOfProcessors, SystemType, TotalPhysicalMemory |
       Export-Csv -path "$MyPath\$computername.SystemReport.csv" -NoTypeInformation 

       }
  
}

****Code end*****

Rgds

Dee


Dee

Need help making a script for a Win 7 hanging update fix.

$
0
0

If someone knew how to make a batch file or script to do the following, this fix prevents windows updates from hanging which is quite common. Here's the fix:

stop B.I.T.S (Background Intelligent Transfer Service) and Windows Update
in Services.msc.
Install kb3172605 through the standalone installer.

Restart PC 
stop B.I.T.S (Background Intelligent Transfer Service) and Windows Update
in Services.msc.
Install kb3135445 through the standalone installer. 
Make
sure B.I.T.S, Windows Installer, Windows Updates, and Windows Modules Installer
are all set to AUTOMATIC within services.msc.
Restart PC.

azure powershell - newly created vm networkprofile not available?

$
0
0

i am using azure powershell 2.0.1.  when i create a new vm, the vm's network profile does not seem to be available within the same azure powershell session.  if i run the same code from a new session (after vm created), it returns just fine.  how can i get the network profile information within the same session?  thanks.

example:

#$vmconfig includes typical options for deploying vm
$vm = New-AzureRmVm -location $azureregion -resourcegroupname $resourcegroupname -vm $vmconfig

#during session where vm is created as above, below is an inifinite loop, NetworkProfile never returns/contains data!
do
{
        $vm = Get-AzureRmVm -resourcegroupname $resourcegroupname -name $vmname
        $nicReference = $vm.NetworkProfile.NetworkInterfaces
}
while (!$nicReference)

Editing a csv file

$
0
0
Hi guys,

Is there any way to edit a csv file through powershell ?

I would to remove some row and columns, and remove some blank values.

I think that is possible find the blank values, searching for ";;;". But I don't know how to do.

Thanks in advance.

Passing variables to function fails - empty variable

$
0
0

I am having trouble with passing variables to a function. I've used Debug statements and manually debugged it myself by tracing it. The variable is non empty before the function call, but once I get into the function, it is null. I'm lost. I've looked at the code over and over again and I can't figure out what I'm doing wrong. I'm sure it's something obvious, but I just need another set of eyes to show me.

Brian

function main
{



	#region test database connectivity
	#test-databaseRead
	#endregion

	#region add to exclusion list, add to SCCM apps list
	#Add-ToExclusions
	#endregion


	#region function scoped variables
	$computerNames = Get-Content "X:\ircstm\PCTechs\EUC Central Services\Refresh Script\Computers.txt"
	$GarbageApps = Get-Content -path "X:\ircstm\PCTechs\EUC Central Services\Refresh Script\GarbageApps.txt"
	$SCCMApps = Get-Content -path "X:\ircstm\PCTechs\EUC Central Services\Refresh Script\SccmApps.txt"

...


Add-RemoteDataToTemp -computerName $computerName -SSCMApps $SCCMApps -GarbageApps $GarbageApps -temp $temp

...

function Add-RemoteDataToTemp ($computerName, $SCCMApps, $GarbageApps, $temp)
{

...

$installedApps = $(Get-Apps -computerName $computerName)
		Write-Debug "InstalledApps= $installedApps"

		Get-AppsToInstall -installedApps $installedApps -SCCMApps $SCCMApps -GarbageApps $GarbageApps -sccmAppsToInstall $sccmAppsToInstall -manualAppsToInstall $manualAppsToInstall

...

}

unction Get-AppsToInstall ($installedApps, $SCCMapps, $GarbageApps, $sccmAppsToInstall, $manualAppsToInstall)
{
	$installedApps | ForEach-Object {
		$currentApp = $_
		if (Compare-Object -ReferenceObject $currentApp -DifferenceObject $SCCMapps -IncludeEqual -ExcludeDifferent)
		{
			$sccmAppsToInstall += $currentApp #in master SCCM app list
		}
		else
		{
			if (!(Compare-Object $currentApp $GarbageApps -IncludeEqual -ExcludeDifferent))
			{
				$manualAppsToInstall += $currentApp  #NOT in master Garbage app list
			}
		}
	}

}

Is it possible to list all servers with specific role installed using Powershell on Servers WS2012 and WS2008 ?

$
0
0

Hi,

I am wondering if I can list all servers which have print-server role installed. I have written script which is based on Get--Windowseature bat as far as I know It doesn't work on Windows 2008 as long as those servers don't have Server Manager role installed. I have a lot of servers so I cannot just install this role on all of them.

Maybe Invoke command? Or other command which works for both versions (2008 and 2012)

I will copy my script if you wish.

Any ideas?

Thanks in advance.


Learn PowerShell Now

PowerShell Script Errors: "Cannot find path 'C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLProvider.Types.ps1xml' because it does not exist."

$
0
0

This error *appers* to occur on machines:

Do SQL 2008 Tools put something in the user's profile that would cause this?


Darwin ____________________ CSI:\> windows Put Apps On Win7 and Virtualization http://csi-windows.com/courses

How to get disk capacity info on remote server displayed in size like GB/TB?

$
0
0

I can use PS to get the remote server disk capacity and free space, but how do I get the size displayed in GB or TB? See picture, thanks.


Thang Mo

how can export the errors in powerhselll query

$
0
0

Hi 

I am quering users in AD but the users cannot find in AD, get error in RED on PowerShell cmdlets

I want to  export or take thatparticular object in output file.

see below snapshot.

System.Security.Cryptography.SHA256CryptoServiceProvider

$
0
0

I am trying to execute this line in powershell on windows 2008 R2 ( freshly installed system. Haven't installed patches yet ).

$sha256 = New-Object -TypeName System.Security.Cryptography.SHA256CryptoServiceProvider

But i am getting an error "Cannot find type [System.Security.Cryptography.SHA256CryptoServiceProvider] : Make sure the assembly containing this type is loaded ".

Is there any specific package/patch that I need to install in order to get it to work ?

Viewing all 21975 articles
Browse latest View live


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