Quantcast
Channel: Windows PowerShell Forum
Viewing all 2562 articles
Browse latest View live

How do I format and perform logic after a scriptblock runs via PS remoting?

$
0
0

Hello,

I run the following Powershell Remoting command and I get a list of machines in a Powershell list format.  All I'm looking to do is take the output and 1.) Count the number of machines, and 2.)Display in a Table with just PSComputerName and ServicePackMajorVersion.

I've tried some table logic and counting after the where clause via 'piping', but I wasnt successful and I dont understand why I cant do it.  Any ideas?  Im basically unclear on how to work with the results of a scriptblock being executed via PS remoting.  Thanks in advance.

$Sessid = New-Pssession $MyDCs
Invoke-Command -session $Sessid -scriptblock {GET-WMIOBJECT win32_operatingsystem | 
                 SELECT-OBJECT Name,ServicePackMajorVersion,ServicePackMinorVersion | 
                 where {$_.ServicePackMajorVersion -ne 1} }


Thanks for your help! SdeDot


Loop through directory and call .Net gacutil to register assembly

$
0
0

Noob here. I've tried several different examples but I can't get anything to work. I could use the cmd line to do is but I'm trying to learn a little powershell. Thanks for your help. Here's what I have so far.

$GACUtil = "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\gacutil.exe" $DLLPathCore11 = "\\buildmachine\CommonLibraries\Main\Core\1.1\CHI*.dll"

#add gacutil to path $oldPath=(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).Path $newPath=$oldPath+$GACUtil #write-output "new path: " + $newPath Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH –Value $newPath ls $DLLPathCore11 | Foreach -Process { $extjob = New-Object System.Diagnostics.Process $extjob.StartInfo = New-Object System.Diagnostics.ProcessStartInfo $args = "/if " + $_.name $returnexitcode = $false $extjob.StartInfo.FileName = $GACUtil $extjob.StartInfo.Arguments = $args $extjob.StartInfo.UseShellExecute = $shell $extjob.StartInfo.WindowStyle = 0 $extjob.StartInfo.RedirectStandardOutput = $true $null = $extjob.Start() $extjob.WaitForExit() $returnexitcode = $extjob.ExitCode $resulttxt = $extjob.StandardOutput.ReadToEnd() # write-output "filename: " + $_.name write-output "exit code:" + $returnexitcode }



-Will

Code Signing

$
0
0

I have an internal CA (2008 Standard, non-r2) with the code signing template available.  I generated a code signing certificate and signed a powershell script I've made.  When I try to run it on a domain member (that automatically trusts the CA), I still get the following prompt: "blah.ps1 is published by blah and is not trusted on your system.  Only run scripts from trusted publishers.  [V] Never run, [D] Do not run, [R] Run once [A] Always Run [?] Help"

I was assuming since it was signed with a certificate from the internal CA that it would automatically be trusted.  What am I missing here?

Thanks 

How to keep blank lines from being used as input?

$
0
0

I’m trying to write a simple script to clean up some directories.  However, I don’t want to delete all directories, only the ones in my text file.

Problem- if my text file has a blank line, then I am basically telling my script to delete everything under the parent.  Any way to keep this from happening? (it's easy to have an extra return at the end, or just a blank line somewhere, and I want to safeguard against that).

 

Example- I want to delete users/jdoe but not users/tgun

 

However, if there is a blank line, everything under the users folder gets deleted including tgun. L

 

Current script-

 

 

foreach ($folder in get-content c:\script\deletefolders.txt)

{

               get-childitem c:\users\$folder -recurse |remove-item -recurse -confirm:$false

              "Deleted folder $folder"

 

}

What are the recommended 'poor man' Powershell script versioning software options?

$
0
0

Hello,

I've developed many Powershell scripts and they reside on various servers and workstations across domains all over the globe.  I'd like to keep a 'master' copy on my Win7 desktop and 'version' them.  I only use the MS ISE and the command line to run my scripts and will continue to do so.  Any suggestions on recommended 'poor man' (ie. no cost) Powershell script versioning software options?


Thanks for your help! SdeDot


IIS Config

$
0
0

I'm trying to list part of the my IIS configuration on a remote server.  I would like to be able to get website name and all its applications, the website path, and the enabled authentication methods for each site and application.  I'm able to get parts of this but I'm not experienced enough to put them together, can someone help.

# I can list the website with the following

$server = 'servername'
$names = Invoke-Command -ComputerName $server {Import-Module WebAdministration; Get-website | select name}

# I can list the applications with the following

$server = 'servername'
$names = Invoke-Command -ComputerName $server {Import-Module WebAdministration; Get-website | select name}
$results = foreach ($name in $names){
invoke-command -ComputerName $server {import-module webadministration; Get-WebApplication -site "$name" | select *}
}
foreach ($result in $results){
$result.path.trim('/')
}

Thanks

Invoke-Command Start-Job Execution Issue

$
0
0

I'm trying to execute an EXE on multiple machine as follows:

If($Session)
{        
    Invoke-Command -session $session -scriptblock {
    $executable = "cmd.exe"
    $args = "/c `"C:\Shared\My.exe`""
    $p = Start-Process -FilePath $executable -ArgumentList $args -Wait -PassThru}   
}

And the above code works charm - Since the EXE execution takes long time, I would like to do multi threading to invoke the command parallel in other machines. And i tried the following commands  but no luck.

Invoke-Command -session $session -scriptblock {start-job -scriptblock { 
$executable = "cmd.exe"
$args = "/c `"C:\Shared\My.exe`""
$p = Start-Process -FilePath $executable -ArgumentList $args -Wait -PassThru}}

Appriciate any help and Thanks in advance.


Vijesh Ollithodi

Powershell Remoting Unable to load assembly "-" Weird

$
0
0

I have been trying to use powershell remotely, but I get a strange error when attempting to use the simplest commands. I have tried various solutions, but I will not post them here, because I want all suggestions. Any help is greatly appreciated. I am at a client and need to get this figured out.

 

Attempt 1:

 

PS C:\Windows\system32> enter-pssession server01

Enter-PSSession : Processing data from remote server failed with the following error message: Unable to load assembly "

-" specified in "InitializationParameters" section. For more information, see the about_Remote_Troubleshooting Help top

ic.

At line:1 char:16

+ enter-pssession <<<<  mmi-mscsmd0-phx

    + CategoryInfo          : InvalidArgument: (mmi-mscsmd0-phx:String) [Enter-PSSession], PSRemotingTransportExceptio

   n

    + FullyQualifiedErrorId : CreateRemoteRunspaceFailed

 

 

Attempt 2:

 

PS C:\Windows\system32> invoke-command -computername localhost -scriptblock {get-culture}

[localhost] Processing data from remote server failed with the following error message: Unable to load assembly "-" spe

cified in "InitializationParameters" section. For more information, see the about_Remote_Troubleshooting Help topic.

    + CategoryInfo          : OpenError: (:) [], PSRemotingTransportException

    + FullyQualifiedErrorId : PSSessionStateBroken


Brody Kilpatrick brodykilpatrick at gmail dot com

Way to list all external

$
0
0

We have several PowerShell scripts that are very large, and are linked to external scripts.
Is there a way to get a list of all external .PS1 scripts that is reaches out to, so that we can clean up any excess scripts that are lingering without breaking the core script.

In other words, we have a bunch of scripts in a directory.  We have a man script, but I need to see which scripts in that directory that it reaches out to (which ones are essential for it to run), without deleting anything that it may use.

Is there a way to run a command against it to see which files or other .PS1 files that it may invoke when running.  I would like to get rid of all the extra/unneeded files that are not accessed by the script.

AD DS

$
0
0

Hi,

Possible How to create a single PowerShell script

1. Changing the Hostname

2. Creating a New forest Domain, DNS and IIS in single PowerShell script.

- Kadhar Khan

Help with gettting script to get installed software via registry working

$
0
0

I started out using the WMI. This works because I specify "$_" after computer

$date = Get-Date -f MMddyyyy
$computer = get-content C:\Users\Public\Documents\computers_12172012.csv
$computer | ForEach-Object {
    $product = gwmi -Query "Select __SERVER,Caption,Name,Vendor,IdentifyingNumber From win32_Product Where Name Like '%mysoftware%'" -Computer $_
    $product | Select   @{Label='UserName';Expression={gwmi -Query "Select UserName From win32_ComputerSystem" -Computer $_.__SERVER | Select -expand  UserName}},
                        @{Label='Computer';Expression={$_.__SERVER}},
                        @{Label='Caption';Expression={$_.Caption}},
                        @{Label='Vendor';Expression={$_.Vendor}},
                        @{Label='Version';Expression={$_.Version}}
    } | Export-CSV $("C:\Users\Public\Documents\InstalledSoftware\mysoftwareInstalls_"+$date+".csv") | Format-Table -Auto

I've found that searching the registry is faster. I've tried what's below and only scans my computer.  Is there a way to pipe the "$pc"? I've also tried the scriptblock/invoke-command method and it hit and miss. Not all of the information in writing to the file. Computers are set up PS remoting in GP and working.

$date = Get-Date -f MMddyyyy
$computers = Get-Content C:\Users\Public\Documents\computers_12172012.csv
Foreach ($pc in $computers)
{
   $product = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where {$_.DisplayName -like '*java*'}
   $product | Select @{Label='Computer';Expression={Get-Item Env:\COMPUTERNAME | Select -ExpandProperty value}},
                     @{Label='Display Name';Expression={$_.DisplayName}},
                     @{Label='Version';Expression={$_.DisplayVersion}},
                     @{Label='Publisher';Expression={$_.Publisher}},
                     @{Label='Uninstall';Expression={$_.UninstallString}} | 
              Export-CSV $("C:\Users\Public\Documents\InstalledSoftware\javaInstallations"+$date+".csv") | Format-Table -Auto
}


Saving as delimited CSV data

$
0
0

Hello Geeks!

Yesterday, I learnt, from Kazun, how to convert plain CSV file into delimited file, as below:

function ToDelimtedCSVFile ($FileName)
{
    Import-CSV $FileName `
            -Delimiter ":" -Header Name, Value | `
            Export-CSV $FileName -NoTypeInformation -UseCulture
}

I just wonder, there must be a way to save data directly into delimited (split into 2 columns) CSV file, instead of first saving it as a plain data, then Import and  convert it!

Would a geek help me with this process, please!




InvokeMethodOnNull

$
0
0

I am getting the error you cannot call a method on a null-values expression

Get-QADGroupMember "Primary Workstations" | Where {($_.ManagedBy -match "Disabled Accounts") -or ($_.ManagedBy -eq $null)} | Sort managedby | % {
        $managedby = $_.ManagedBy
        $splitman = $managedby.split(",")[0]
        $name = $splitman.split("=")[1]
       }

I am probably doing something wrong

1) The code below returns in this case two members but with a FQDN. How do I make sure I split the names so I only have the names and make sure I assign it to a variable so it has both names (in this case) or if it returned 10 so it has the 10 names after the split. Get-QADGroupMember "Primary Workstations" | Where {($_.ManagedBy -match "Disabled Accounts") -or ($_.ManagedBy -eq $null)} | Sort managedby | % {$_.ManagedBy}.

2) The second is how do I get rid of this error in the future. Thank you

File Permissions Report not working

$
0
0

I have been tasked with generating a report that contains folder permissions. The problem im running into  is these errors:

Get-ChildItem : The specified path, file name, or both are too long. The fully
qualified file name must be less than 260 characters, and the directory name mu
st be less than 248 characters.

Get-ChildItem : Access to the path '\\path\share$\CSR\Compliance' is denied.
At E:\Scripts\GetAllACL.ps1:15 char:34
+  [Array] $folders = Get-ChildItem <<<<  -path $path -force -recurse | Where {
$_.PSIsContainer}

Here is the script I am using:

#Set variables


$path=Read-Host"Enter the path you wish to check"


$filename=Read-Host"Enter Output File Name"


$date=Get-Date



#Place Headers on out-put file


$list="Permissions for directories in: $Path"


$list|format-table|Out-File"C:\Powershell\Results\$filename"


$datelist="Report Run Time: $date"


$datelist|format-table|Out-File-append"C:\Powershell\Results\$filename"


$spacelist=""


$spacelist|format-table|Out-File-append"C:\Powershell\Results\$filename"



#Populate Folders Array


[

Array]$folders=Get-ChildItem-path$path-force-recurse|Where{$_.PSIsContainer}



#Process data in array


ForEach($folderin[Array]$folders)

{

#Convert Powershell Provider Folder Path to standard folder path


$PSPath=(Convert-Path$folder.pspath)

$list=("Path: $PSPath")

$list|format-table|Out-File-append"C:\Powershell\Results\$filename"



Get-Acl

-path$PSPath|Format-List-propertyAccessToString|Out-File-append"C:\Powershell\Results\$filename"


}

#end ForEach

Any help would be appreciated.

I'm unable to add/import the Failover Clustering Powershell module in Windows 7

$
0
0

I am unable to load the failover cluster module on my Win 7 machine because it isn't listed. I've installed RSAT SP1 and have enabled the Failover Clustering Tools feature. I can see/access the Failover Cluster Manager gui in my admin tools folder. I have the x64 version of Win 7 installed on my system. I disabled and re-enabled the Failover Clustering Tools feature and I still can't see the FailOver module when I run Get-Module -ListAvailable. It just isn't there.

What am I missing?



PowerShell scripting with logical conditions

$
0
0

Hello,

I am completley new to powershell so i really need some help with a script i would like to make. the script i am trying to make will do the following for a virtual machine running under Hyper-V on server 2012 or Windows 8

  • check the path of the drive which is currently mounted to the VM on the SCSI controller at the specified controller location
  • check if this path matches the path to a VHD from one of two USB drives (only one USB drive will be attached to the host any one time, it will either have the drive letter Y or X, or can we use the drive GUIDs?)
  • if the path for the VHD on the VM is the same path as the VHD on the currently connected USB drive, then the USB drive has not yet been swapped, so exit the script
  • if the path to the VHD on the VM is different to that of the VHD on the currently connected USB drive then the USB drive has been swapped, so change the VHD attached to the VM to that of the USB drive

I havent got a clue about variables or conditional statements in PowerShell, but so far i have the following two commands.... when i run this first one it produces a table, one of the columns is Path which i am guessing i will need to store in a variable and compare to the USB drive connected....
Get-VM Test | get-VMHardDiskDrive -ControllerType SCSI -ControllerNumber 0

this following command does the job of replacing of the currently attached vhd with that from the Y drive.... 

Set-VMHardDiskDrive -VMName Test –ControllerType SCSI -ControllerNumber 0 -ControllerLocation 0 -Path "Y:\MyVHDS\Drive1.vhdx"

the command below will change it to the VHD on drive X....

Set-VMHardDiskDrive -VMName Test –ControllerType SCSI -ControllerNumber 0 -ControllerLocation 0 -Path "X:\MyVHDS\Drive2.vhdx"

can someone make sense of all this and do some wizzy magic to make my mess turn into something neat and tidy :)?

thank you very much for any help

Powershell nslookup -

$
0
0

I found the following powershell using ping and nslookup from the following webpage:  http://blog.securitywhole.com/2009/09/23/powershell-nslookup-brute-force.aspx

for (/L %i in (1,1,255) do @echo 10.10.10.%i: & @nslookup 10.10.10.%i 2>nul | find "Name")

But I'm receiving an error with regards to the &:

Ampersand not allowed. The & operator is reserved for future use; use "&" to pass ampersand as a string.

At line:1 char:48

Missing statement body in for loop.
At line:1 char:93

But if I wrap the & in "&" I receive an error:

Missing statement body in for loop.
At line:1 char:95
What have I done wrong with regards to the &?

Task Manager - reducing multiple processes to one process using powershell?

$
0
0

I am running a .ps1 script that simultaneously executes 5-10 excel files. Is there a possibility of reducing multiple instances of excel files from task manager (EXCEL.EXE *32) to only one process using powershell?

I dont want to kill the remaining processes, i just want one to be displayed for all instances that are running. Is this possible?

Thanks,

(begineer) Check if the file exists on the remote server

$
0
0

Hi,

I am trying to check if the file exists on remote server.

I will connect to one of the servers, I have list of server_name and File_name (each server can have many files that I need to check).

If the file exists then I need to add 1 as new column in the csv file, if it does not then put 0 in new column.

So input csv will look like this

Server_name, file_name

server1,file1

server1,file2

Server2, file3 etc

Output csv

Server_name, File_name, ifexists

How do I script this?

Thanks for the help.


RPSAdmin

Old Unix Admin needs Powershell equivalent command

$
0
0

I am migrating own of primary applications from a Unix environment to Windows 2008R2.. Have been doing Unix for 25 years, and need to bring myself up to speed or re-write my resume. :-o

I have created HOMEDIR in a file system D:\Home\groupname\<userfirstname.userlastname> (where userfirstname.userlastname = AD account name) 

As it stands the application needs Full permissions for each AD user to this home directory. 

In Unix I would write a shell script to recurse the /home/groupname and set permissions in a few lines of code,

Example

#!/bin/sh

cd /home/groupname

for dirname in `ls`

do

chown $dirname $dirname

chown -R 770 $dirname

done

Is there something I can do in powershell to do this?

any thoughts appreciated

Viewing all 2562 articles
Browse latest View live


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