I'm currently creating a script for a group of users could use it. I use Test-Path "C:\Users\vincentw\allapps.txt to verify if allapps.txt exists on my local system before running the script:
if (!(Test-Path "C:\Users\vincentw\allapps.txt")) {
"All sw/apps" >> allapps.txt
"-------------------------------------------------------" >> allapps.txt
(Get-WmiObject Win32_Product |
where {$_.Vendor -notmatch "Advanced"} |
Format-List name, Vendor, Version |
Out-String).Trim() >> allapps.txt
"-------------------------------------------------------" >> allapps.txt
} else {
Write-Host "WARNING: File already exists!"
break
}
However, the script verifying only works on my local system. I'm wondering is there any way my local username - 'vincentw' could be replaced to make the script available check every user's local path on their own systems?
If the script will be run from their user on their computer then you could use $env:USERPROFILE
Test-Path "$($env:USERPROFILE)\allapps.txt"
If you want to do it on all profiles you can do something like this
Get-ChildItem "C:\Users\" -Directory | foreach-object{
If(!(test-path "$($_.FullName)\allapps.txt")){
"Missing : $($_.FullName)\allapps.txt"
}Else{
"Found : $($_.FullName)\allapps.txt"
}
}
Related
My PowerShell script just checks multiple servers to make sure the input* and output* directories are clear of any files.
I'm simply trying to output to console the results of a GCI call prior to throwing an error message. However, when I uncomment the "throw" line, the $inputFiles and $outputFiles no longer output to the console. Below is the code:
$allServers = #(
"server1.com",
"server2.com")
foreach ($server in $allServers) {
$inputFiles = Get-ChildItem -Path "\\$server\C$\jobs\statements\input*\" -Recurse | Where-Object {! $_.PSIsContainer } | Select FullName
$outputFiles = Get-ChildItem -Path "\\$server\C$\jobs\statements\output*\" -Recurse | Where-Object {! $_.PSIsContainer } | Select FullName
if ($inputFiles -eq $NULL -and $outputFiles -eq $NULL) {
Write-Host "Environment is ready for statement processing."
}
else {
Write-Host "Environment is NOT ready for statement processing."
Write-Host "The following files exist in input/output: `n"
$inputFiles
$outputFiles
#Throw "Files exist in input/output. See above for details."
}
}
Below is the console output:
Environment is NOT ready for statement processing.
The following files exist in input/output:
Environment is NOT ready for statement processing.
The following files exist in input/output:
FullName
--------
\\server1.com\C$\jobs\statements\input\asdasd.txt
\\server1.com\C$\jobs\statements\input_254\asdasd.txt
\\server1.com\C$\jobs\statements\input_test\asdasd.txt
\\server2.com\C$\jobs\statements\input\CUSSTAT10302021.245
\\server2.com\C$\jobs\statements\input\CUSSTAT11312021
\\server2.com\C$\jobs\statements\input\CUSSTAT11312021.zip
And below is the console output when I uncomment the "throw" line:
Environment is NOT ready for statement processing.
The following files exist in input/output:
Files exist in input/output. See above for details.
At C:\jobs\statements\bin\Statements-EnvironmentCheck.ps1:47 char:9
+ Throw "Files exist in input/output. See above for details."
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Files exist in ...ve for details.:String) [], RuntimeException
+ FullyQualifiedErrorId : Files exist in input/output. See above for details.
I know I have some error output cleanup to perform in order to include all the servers that might have files present, but please ignore that for now.
What you're experiencing is explained in this answer and this answer, basically you need to implement Out-Host \ Out-Default:
$inputFiles, $outputFiles | Out-Host # Should fix the problem
# possibly `throw` might require this too
throw "Files exist in input/output. See above for details." | Out-Host
However, I feel is worth showing you a better way to approach your code, returning a unified array of objects which you can filter, sort and export.
$allServers = #(
"server1.com"
"server2.com"
)
$result = foreach ($server in $allServers) {
# use `-File` instead of `! $_.PSIsContainer`
$out = #{
in = Get-ChildItem "\\$server\C$\jobs\statements\input*\" -Recurse -File
out = Get-ChildItem "\\$server\C$\jobs\statements\output*\" -Recurse -File
}
# if $out['in'] and $out['out'] are `$null`, Ready is `$true`
[pscustomobject]#{
Ready = -not($out['in'] -or $out['out'])
Server = $server
Files = $out
}
}
Now, if you want to see which servers are Ready (no files in input and output):
$result.where{ $_.Ready }
And if you want to see which servers are not Ready, and have a list of the files:
$result.where{ -not $_.Ready }.foreach{
foreach($file in $_.Files.PSBase.Values.FullName) {
[pscustomobject]#{
Server = $_.Server
Files = $file
}
}
}
Actual File Configuration:
clustername=GLA-CLU2
fswmain=\DC01\SQL-FSW1
fswdr=\DC01\SQL-FSW2
My actual script:
### BEGIN OF Passing as Variables, the configuration values separated with '=' and Retrieved from the indicated TXT file:
Get-Content '.\FSW_pathConf.txt' | Foreach-Object {
$Vconfvalue = $_.Split('=')
New-Variable -Name $Vconfvalue[0] -Value $Vconfvalue[1] }
### END OF Passing values as Variables
### Testing Each Path defined into configuration file
$currentfsw = Get-clusterresource -cluster $clustername | where-object {$_.ResourceType -like "File Share Witness"} | get-clusterparameter -Name "sharepath" | Select Value
Write-Host "`r"
Write-Host "the current file share witness configuration On Cluster: '$($Clustername)' is: '$($currentfsw)' "
if($currentfsw -is "$fswmain") {Test-Path -Path "$fswmain" -IsValid}
else{Set-ClusterQuorum -Cluster $Clustername -NodeAndFileShareMajority "$fswdr"}
if($currentfsw -is "$fswdr") { Test-Path -Path "$fswdr" -IsValid}
else{Set-ClusterQuorum -Cluster $Clustername -NodeAndFileShareMajority "$fswmain" }
What I would like to do whcih im struggling with:
if $fswmain is valid then return "OK,current fsw is working" and stop this script here
If not $currentfsw is no valid then run the command below to swith to $fswdr
Then, only if $currentfsw is not equal to $fswmain
if $fswdr is valid then return "OK,current fsw is working" and stop this script here
If not run the command below to switch to $fswmain
Any could bring some help here ? I am quite new with powershell and sysadmin
Thank you.
I am trying to search all user's desktops for a particular shortcut and I find difficulties enumerate all desktop paths for different users on the computer as some of them have OneDrive sync and the standard path c:\Users\%user%\Desktop is not to be found.
I have tried getting the path with the GetFolderPath which only returns the path to the current user:
[System.Environment]::GetFolderPath("Desktop")
So briefly the path scenarios are:
C:\users\username\Desktop
C:\users\username\One Drive - Company\Desktop
I would be glad if somebody has a hint how to find all paths in this mixed environment.
Here's my older training script. I don't know how (or if any) it works with OneDrive cync as I have OneDrive disabled (or even uninstalled) because I found it extremely irritating…
Remove-Variable path -ErrorAction SilentlyContinue
Write-Verbose "--- Special Folders ---" -Verbose
$SpecialFolders = #{}
$names = [Environment+SpecialFolder]::GetNames( [Environment+SpecialFolder])
ForEach ($name in $names) {
# assign and then check
if( $path = [Environment]::GetFolderPath($name) ){
$SpecialFolders[$name] = $path
} else {
Write-Warning $name
$SpecialFolders[$name] = ''
}
}
$SpecialFolders.GetEnumerator() |
Sort-Object -Property name #| Format-Table -AutoSize
"---"
###Pause
$ShellFolders=#{}
Write-Verbose "--- Shell Folders ---" -Verbose
[System.Enum]::GetValues([System.Environment+SpecialFolder]) |
ForEach-Object {
$ShellFolders[$_.ToString()] =
($_.value__, [System.Environment]::GetFolderPath($_))
}
$ShellFolders.GetEnumerator() |
Sort-Object -Property name # | Format-Table -AutoSize
I have written a script which checks a service status, tests two paths and also tests a registry value. Currently I am getting output on the power shell console (that could be because I am using write-output command).
Is there any way to write the single one page output to a file?
I am struggling to find a way to out-file entire output to a file.
Below is the script.
$testpath = Test-Path "C:\test"
$testpath2 = test-path "C:\test"
$mcshieldk = Get-Service -Name mcshield | select Name
$internet = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\internet explorer").MkEnabled $hostname = hostname Write-Host "hostname of comuter is" $hostname if (Test-Path $Machinetype)
{}
else { Write-Host "internet is" $internet }
if ($testpath -eq $true -and $testpath2 -eq $true)
{ Write-Host "test and test1 folder exists" -ForegroundColor Green }
else{ Write-Host "folder does not exists" -ForegroundColor Red } if($mcshield.Name -eq "mcshield") { Write-Host "mcshield service exists" }
else { Write-Host "mcshield does not exists" }
Below is the console output
hostname of comuter is Server1
internet is Yes
test and test1 folder exists
mcshield does not exists
Swap out your Write-Host cmdlets or add in another line with the following:
"Your output text $YourVariable" | Out-File -FilePath "C:\Log.txt" -Append -Encoding utf8
This will append a string to the end of the log file C:\Log.txt. Note, missing the -Append parameter will cause the file to be overwritten.
You can also use the follow to give the same affect:
"Your output text $YourVariable" >> "C:\Log.txt"
But be carefully not to mix the two methods as you might get encoding errors in the text file. If you wish to overwrite the file with the second method use > instead of >>.
I'm trying to create a mount point using Powershell. it's done locally, and here is the code & issue i'm having.
$choice = "t"
New-Item -ItemType directory -Path "E:\Data\Riptide\Ariis\Ris\Docs\interPrimary1\"
$orgdrive = "E:\Data\Riptide\Ariis\Ris\Docs\interPrimary1\"
$driveLetter= $Choice + ":\"
$driveinfo=get-wmiobject win32_volume | where { $_.driveletter -eq $choice + ":" } | select-object DeviceID
Mountvol $orgdrive $driveinfo
When executed, I get that the parameter is incorrect.
Thanks in advance.
You just have to try :
mountvol $orgdrive $driveinfo.DeviceID
For the future you can test :
$driveinfo| Get-Member
You can find here a tool that allow you to test the command line parameters.